using System;
using AlicizaX.UI.Extension;
using UnityEngine;
using UnityEngine.UI;

namespace AlicizaX.UI
{
    public abstract class ViewHolder : MonoBehaviour
    {
        private RectTransform rectTransform;

        public RectTransform RectTransform
        {
            get
            {
                if (rectTransform == null)
                {
                    rectTransform = GetComponent<RectTransform>();
                }

                return rectTransform;
            }
            private set { rectTransform = value; }
        }

        public string Name { get; internal set; }
        public int Index { get; internal set; }

        public bool ChoiseState { private set; get; }

        public Vector2 SizeDelta => RectTransform.sizeDelta;
        private IButton _button;

        protected internal virtual void OnStart()
        {
        }

        protected internal virtual void OnRecycled()
        {
        }

        public abstract void BindViewData<T>(T data);

        protected internal virtual void BindItemClick<T>(T data, Action<T> action)
        {
            if (_button is null && !TryGetComponent(out _button))
            {
                Log.Warning("找不到Button组件");
                return;
            }

            _button.onClick.RemoveAllListeners();
            _button.onClick.AddListener(() => action?.Invoke(data));
        }

        protected internal void BindChoiceState(bool state)
        {
            if (ChoiseState != state)
            {
                ChoiseState = state;
                OnBindChoiceState(state);
            }
        }

        protected internal virtual void OnBindChoiceState(bool state)
        {
        }
    }
}
