using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class TableRowController : MonoBehaviour {
    public TableRowClickDetector ClickDetector => GetComponent<TableRowClickDetector>();
    public TableRowHoverDetector HoverDetector => GetComponent<TableRowHoverDetector>();

    public EagleCommonTextures CommonTextures =>
            gameObject.GetComponentInParent<EagleCommonTextures>();

    private bool _selected = false;
    public bool Selected {
        get => _selected;
        set {
            _selected = value;
            ColorRow();
        }
    }

    private bool _shadeOn = false;

    private Color _backgroundColor = Color.white;
    virtual public Color BackgroundColor {
        get => _backgroundColor;
        set {
            _backgroundColor = value;
            ColorRow();
        }
    }

    public bool Selectable {
        get => ClickDetector != null && ClickDetector.selectable;
        set {
            if (ClickDetector != null) ClickDetector.selectable = value;
            if (!value) Selected = false;
            ColorRow();
        }
    }

    public bool RightSelectable {
        get => ClickDetector != null && ClickDetector.rightSelectable;
        set {
            if (ClickDetector != null) ClickDetector.rightSelectable = value;
            ColorRow();
        }
    }

    private Color _textColor = Color.black;
    public Color TextColor {
        set {
            _textColor = value;
            foreach (var text in gameObject.GetComponentsInChildren<TMP_Text>()) {
                text.color = _textColor;
            }
        }
    }

    virtual public void ColorRow() {
        if (ClickDetector != null) {
            var newColor = Color.black;
            if (Selected) {
                newColor = Color.blue;
            } else if (!Selectable && !RightSelectable) {
                newColor = Color.gray;
            }

            TextColor = newColor;
        }

        if (_shadeOn) {
            var shadedBackground = new Color(
                    BackgroundColor.r - 0.25f,
                    BackgroundColor.g - 0.25f,
                    BackgroundColor.b + 0.25f);
            gameObject.GetComponent<Image>().color = shadedBackground;
        } else {
            gameObject.GetComponent<Image>().color = BackgroundColor;
        }
    }

    public void ShadeOn() {
        _shadeOn = true;
        ColorRow();
    }

    public void ShadeOff() {
        _shadeOn = false;
        ColorRow();
    }
}
