using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

[Serializable]
public class ChestUIManager : UIBaseManager<Chest>
{
    public new static ChestUIManager Instance { get; private set; }

    public const string ITEM_LOCALIZATION = "UiPanels/";
    public const string PANEL_NAME = "ChestPanel";
    public int SLOTS_NUMBER => 48;

    public string CurrentChestName = null;

    public bool OpenAfterDelay = false;
    public bool CloseAfterDelay = false;

    private IEnumerator coroutine;

    public void Start()
    {
        Instance.keyToOpen = (KeyCode) System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Interaction"));
        ShopUIManager.Instance.keyToOpen = (KeyCode) System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Interaction"));
    }
    public void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public override void Update()
    {
        base.Update();

/*        if (OpenAfterDelay && DynamicPanel == null && CurrentChestName != null && CurrentChestName != "")
        {
            Debug.Log("Open in Update");
            OpenAfterDelay = false;


            // Open additiona panels
            if (!EquipmentUIManager.Instance.GetPanelStatus()) EquipmentUIManager.Instance.OpenPanel();

            if (!InventoryUIManager.Instance.GetPanelStatus()) InventoryUIManager.Instance.OpenPanel();

            base.OpenPanel();
        }
        //keyToOpen = (KeyCode) System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Interact"));


        if (CloseAfterDelay && DynamicPanel != null && CurrentChestName != null && CurrentChestName != "")
        {
            CloseAfterDelay = false;


            base.ClosePanel();

            ChestContentUIManager.Instance.DynamicPanel = null;

            // Close additionals panels
            if (EquipmentUIManager.Instance.GetPanelStatus()) EquipmentUIManager.Instance.ClosePanel();

            if (InventoryUIManager.Instance.GetPanelStatus()) InventoryUIManager.Instance.ClosePanel();
        }*/

    }

    public override bool OpenPanel()
    {
        if (CurrentChestName == null || CurrentChestName == "")
        {
            Debug.Log($"You re not in collision with any chest");
               
            return false;
        }


        // Animacje otwierania
        OpeningAnimate();

        StartCoroutine(OpenWithDelay(0.3f));

        return true;
    }

    public override bool ClosePanel()
    {
        if (CurrentChestName == null || CurrentChestName == "")
        {
            return false;
        }

        base.ClosePanel();

        ChestContentUIManager.Instance.DynamicPanel = null;

        // Close additionals panels
        if (EquipmentUIManager.Instance.GetPanelStatus()) EquipmentUIManager.Instance.ClosePanel();

        if (InventoryUIManager.Instance.GetPanelStatus()) InventoryUIManager.Instance.ClosePanel();

        // Animacje zmykania
        ClosingAnimate(CurrentChestName);
        StartCoroutine(CloseWithDelay(0.3f, CurrentChestName)); // delay to display closing without breaking

        //CloseWithDelay(0.3f);

        return true;
    }

    public override void SetupPanel()
    {
        base.SetupPanel();

        var chest = FindChestInCollection(CurrentChestName);
        if (chest == null)
            throw new Exception($"Chest {CurrentChestName} not found");

        ChestContentUIManager.Instance.SetList(chest.GetContent());
        ChestContentUIManager.Instance.DynamicPanel = DynamicPanel;
        ChestContentUIManager.Instance.SetupPanel();

        // setup models list
        //DynamicPanel.GetComponent<ChestPanelController>().SetUp(chest.GetContent());
    }

    public override void UpdateList()
    {
        if (CurrentChestName == null || CurrentChestName == "")
            throw new Exception($"You re not in collision with any chest");


        var chest = FindChestInCollection(CurrentChestName);
        if (chest == null)
            throw new Exception($"Chest {CurrentChestName} not found");

        ChestContentUIManager.Instance.SetList(chest.GetContent());
        ChestContentUIManager.Instance.DynamicPanel = DynamicPanel;
        ChestContentUIManager.Instance.UpdateList();

        //DynamicPanel.GetComponent<ChestPanelController>().BuildPanelContent(chest.GetContent());
    }

    public void UpdateChestContent(string chestName, List<IndexValuePair<int, EquippableItem>> chestContent)
    {
        Elements.Where(chest => chest.name == chestName).ToList().ForEach(chest => chest.SetContent(chestContent));
    }
    
    protected override GameObject GetTemplatePanel()
    {
        // Resources = default path - Asset/Resources ... .obj
        return Resources.Load(ITEM_LOCALIZATION + PANEL_NAME) as GameObject;
    }

    private Chest FindChestInCollection(string _chestName)
    {
        return Elements.Find(chest => chest.Name == _chestName);
    }

    #region Animation API
    private IEnumerator OpenWithDelay(float waitTime)
    {
        yield return new WaitForSeconds(waitTime);

        // Open additiona panels
        if (!EquipmentUIManager.Instance.GetPanelStatus()) EquipmentUIManager.Instance.OpenPanel();

        if (!InventoryUIManager.Instance.GetPanelStatus()) InventoryUIManager.Instance.OpenPanel();

        base.OpenPanel();
    }

    private IEnumerator CloseWithDelay(float waitTime, string chestName)
    {
        yield return new WaitForSeconds(waitTime);

        ResetingTriggerAnimate(chestName);
    }

    public void OpeningAnimate()
    {
        var currentChest = GameObject.FindGameObjectWithTag("ChestCollection").transform.Find(CurrentChestName);
        
        if(currentChest != null)
        {
            currentChest.GetComponent<Animator>().SetTrigger("OpenIt");
        }
    }

    public void ClosingAnimate(string chestName)
    {
        var currentChest = GameObject.FindGameObjectWithTag("ChestCollection").transform.Find(chestName);

        if (currentChest != null)
        {
            currentChest.GetComponent<Animator>().ResetTrigger("OpenIt");
            currentChest.GetComponent<Animator>().SetTrigger("CloseIt");
        }
    }

    public void ResetingTriggerAnimate(string chestName)
    {
        var currentChest = GameObject.FindGameObjectWithTag("ChestCollection").transform.Find(chestName);

        if (currentChest != null)
        {
            currentChest.GetComponent<Animator>().ResetTrigger("CloseIt");
            currentChest.GetComponent<Animator>().SetTrigger("reactivate");

        }
    }
    #endregion
}