using System;
using System.Collections.Generic;
using Assets.Source.Constants;
using Assets.Source.Misc;
using UnityEngine;

namespace Assets.Source.UI
{
    public abstract class UIElementBase : MonoBehaviour, IUIElement, IReleaseTracker
    {
        [SerializeField] protected bool _openedInitially;
        [SerializeField] protected bool _preventAutoClose;
        [SerializeField] protected string _explicitID = UIConstants.DEFAULT_EXPLICIT_ID;

        public bool OpenedInitially => _openedInitially;
        public bool PreventAutoClose => _preventAutoClose;
        public string ExplicitID => _explicitID;

        public event Action OnRelease;
        public abstract event Action OnOpenStart;
        public abstract event Action OnCloseStart;
        public abstract event Action OnOpenEnd;
        public abstract event Action OnCloseEnd;

        public UIElementState State { get; protected set; }

        public List<IUIElement> ConnectedElements { get; } = new List<IUIElement>();

        public abstract void Open(IUIElementProperties properties = null, bool instantly = false);

        public abstract void Close(bool instantly = false);

        [ContextMenu("Open")]
        private void ContextOpen()
        {
            Open();
        }

        [ContextMenu("Close")]
        private void ContextClose()
        {
            Close();
        }

        void Awake()
        {
            State = UIElementState.Closed;
            gameObject.SetActive(false);
            VAwake();
        }

        void Start()
        {
            VStart();
        }

        void OnDestroy()
        {
            OnRelease?.Invoke();
            VOnDestroy();
        }

        protected virtual void VAwake()
        {
        }

        protected virtual void VStart()
        {
        }

        protected virtual void VOnDestroy()
        {
        }

        public void AddConnectedElement(IUIElement e)
        {
            ConnectedElements.Add(e);
        }
    }
}