using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;

[Serializable()]
public class UnityEventColor : UnityEvent<Color> { }

public class ColorPicker : MonoBehaviour {

    public Image colorPreview;
    public Slider sliderR;
    public Slider sliderG;
    public Slider sliderB;

    public UnityEventColor onColorChanged;

    private Color color = Color.white;
    public Color Color {
        get { return color; }
        set {
            color = value;
            sliderR.value = color.r;
            sliderG.value = color.g;
            sliderB.value = color.b;
        }
    }

    public void SetR(float r) {
        color.r = r;
        ColorChanged();
    }

    public void SetG(float g) {
        color.g = g;
        ColorChanged();
    }

    public void SetB(float b) {
        color.b = b;
        ColorChanged();
    }

    private void ColorChanged() {
        if (!ValidateColor(color)) {
            Color = colorPreview.color;
            return;
        }
        colorPreview.color = color;
        if (onColorChanged != null) {
            onColorChanged.Invoke(color);
        }
        // Dieser Aufruf ermöglicht anderen Komponenten am gleichen Objekt,
        // direkt eine Methode OnColorChanged(Color) zu implementieren und
        // so ohne das Zuweisen von Event-Handlern im Editor auszukommen
        SendMessage("OnColorChanged", color, SendMessageOptions.DontRequireReceiver);
    }

    private bool ValidateColor(Color color) {
        // implement some nice color validation to prevent abuse by Griefers
        return true;
    }
}
