using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Panel : MonoBehaviour
{
    public string key;
    public bool hideBehind;
    public bool stack;

    public PanelGroup group { get; private set; }
    public int index { get; private set; }

    public bool isOpen { get; private set; }
    public bool isTop => group.topPanel == this;

    public event UnityAction onOpen = delegate { };
    public event UnityAction onClose = delegate { };
    public event UnityAction onTop = delegate { };

    private bool didSetup = false;

    public static string GetPanelName(GameObject go, System.Type type) => type.Name == "Panel" ? (go?.name ?? "Panel") : type.Name.Substring(0, type.Name.Length - 5);
    public static string GetPanelName<T>() where T : Panel => GetPanelName(null, typeof(T));

    protected virtual void Setup() { }
    protected virtual void OnOpen() { }
    protected virtual void OnClose() { }
    protected virtual void OnTop() { }

    protected virtual void Awake() { }
    protected virtual void Start() { }
    protected virtual void Update() { }
    protected virtual void LateUpdate() { }
    protected virtual void FixedUpdate() { }

    public virtual void Init(PanelGroup group, int index)
    {
        this.group = group;
        this.index = index;
        _SetOpen(false);
    }
    public void _Setup()
    {
        if (didSetup) return;
        didSetup = true;
        Setup();

        foreach (var item in GetComponents<IPanelSetup>())
            item.SetupPanel(this);
    }

    public void _OnOpen() { OnOpen(); onOpen?.Invoke(); }
    public void _OnClose() { OnClose(); onClose?.Invoke(); }
    public void _OnTop() { OnTop(); onTop?.Invoke(); }

    public void _SetOpen(bool value)
    {
        isOpen = value;
        SetActive(value);
    }

    protected virtual void SetActive(bool value)
    {
        gameObject.SetActive(value);
    }

    public void OpenPanel() => group.OpenPanel(this);
    public void ClosePanel() => group.ClosePanel(this);

    private void Reset()
    {
        key = GetPanelName(gameObject, GetType());
    }
}

public interface IPanelSetup
{
    void SetupPanel(Panel panel);
}
