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

public class EquipmentUIManager : UIWarehouseManager
{
    public override int SLOTS_NUMBER => 9;

    public static new EquipmentUIManager Instance { get; protected set; }
    
    public const string ITEM_LOCALIZATION = "UiPanels/";
    public const string PANEL_NAME = "EquipmentPanel";

    public void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

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

        // setup models list
        DynamicPanel.GetComponent<EquipmentPanelController>().SetUp(Elements);
    }

    public override void UpdateList()
    {
        DynamicPanel.GetComponent<EquipmentPanelController>().BuildPanelContent(Elements);
    }

    protected override GameObject GetTemplatePanel()
    {
        // Resources = default path - Asset/Resources ... .obj
        return Resources.Load(ITEM_LOCALIZATION + PANEL_NAME) as GameObject;
    }

    #region Override list functions

    /// <summary>
    /// Function (SetItemOnPosition) to add slot with its number and item to list (which will be mapped with panel content)
    /// </summary>
    /// <param name="itemOnSlot"></param>
    public override void Add(IndexValuePair<int, EquippableItem> itemOnSlot)
    {
        if (!CheckIfSlotIsInRange(itemOnSlot.Key))
            throw new System.Exception($"Slot number: {itemOnSlot.Key} is out of range, avaiable: {SLOTS_NUMBER} slots");

        if (CheckIfSlotExists(itemOnSlot.Key) && !CheckIfPositionIsEmpty(itemOnSlot.Key))
            RemoveByPosition(itemOnSlot.Key);

        if (itemOnSlot.Value != null)
        {
            Elements.RemoveAll(equipment => equipment.Key == itemOnSlot.Key);
            Elements.Add(new IndexValuePair<int, EquippableItem>(itemOnSlot.Key, itemOnSlot.Value));

            UpdateList();
        }
    }

    public override void RemoveByPosition(int keyPosition)
    {
        if (!CheckIfSlotExists(keyPosition))
            return; // throw new System.Exception($"Slot with number: {keyPosition} don't exist");

        Debug.Log($"Remove from position: {keyPosition}");


        Elements.RemoveAll(equipment => equipment.Key == keyPosition);
        Elements.Add(new IndexValuePair<int, EquippableItem>(keyPosition, null));
    }

    #endregion
}