using UnityEngine;
using UnityEngine.Events;

public class PlayerConfiguration : MonoBehaviour {

    public Color playerColor = Color.white;

    public void Awake() {
        DontDestroyOnLoad(this.gameObject);
        OnLevelWasLoaded();
    }

    public void SetColor(Color newPlayerColor) {
        this.playerColor = newPlayerColor;
    }

    public void OnLevelWasLoaded() {
        if (Application.loadedLevelName.Equals("AStartmenu")) {
            RegisterForColorChanges();
        } else if (Application.loadedLevelName.StartsWith("Level")) {
            WriteColor();
        }
    }

    private void RegisterForColorChanges() {
        GameObject colorPickerObj = GameObject.Find("ColorPicker");
        if (colorPickerObj == null) {
            Debug.LogWarning("Cannot find ColorPicker in scene!", this);
            return;
        }
        ColorPicker colorPicker
            = colorPickerObj.GetComponent<ColorPicker>();
        colorPicker.Color = playerColor;
        UnityAction<Color> setColor
            = new UnityAction<Color>(SetColor);
        colorPicker.onColorChanged.AddListener(setColor);
    }

    private void WriteColor() {
        GameObject tracerObj = GameObject.Find("Tracer-00");
        if (tracerObj == null) {
            Debug.LogWarning("Cannot find Tracer-00 in scene!", this);
            return;
        }
        TracerColor tracerColor
            = tracerObj.GetComponent<TracerColor>();
        tracerColor.playerColor = this.playerColor;
    }

}
