using UnityEngine;
using UnityEngine.UI;

public class BagItem : LogicElementHolder
{
    #region Inspector Elements
    [SerializeField]
    private Transform LogicElementLocation;

    [SerializeField]
    private LogicElementUI LogicElementPrefab;
    #endregion Inspector Elements

    #region Private Variables
    private int Count;
    protected Inventory.Data InventoryData;
    //private TextMeshProUGUI CountText;
    private Text CountText1;
    #endregion Private Variables

    #region Class Functionality
    public void Initialise(Inventory.Data data)
    {
        InventoryData = data;

        if (CountText1 == null)
            CountText1 = GetComponentInChildren<Text>();
        Count = data.Count;


        LogicElementUI logicElement = Instantiate(LogicElementPrefab.gameObject, LogicElementLocation).GetComponent<LogicElementUI>();
        logicElement.Initialise(data.element, this,true);

        UpdateUI();
    }

    public void UpdateUI()
    {
        if (!InventoryData.isInfinit)
            CountText1.text = Count.ToString();
        else
            CountText1.text = "∞";
    }
    #endregion Class Functionality

    #region LogicElementHolder Implementation
    /// <summary>
    /// When a logicElement needs to be added back to this holder
    /// </summary>
    /// <param name="element">Element which is being Added</param>
    public override void OnAdd(LogicElementUI element)
    {
        Destroy(element.gameObject);

        if (!InventoryData.isInfinit)
            Count++;

        UpdateUI();
    }

    /// <summary>
    /// When a LogicElement has started being dragged from this holder
    /// </summary>
    /// <param name="element">Element which is being dragged</param>
    public override void OnRemove(LogicElementUI element)
    {
        if (!InventoryData.isInfinit && Count > 0)
            Count--;
        else if (!InventoryData.isInfinit)
            Destroy(element.gameObject);

        LogicElementUI logicElement = Instantiate(LogicElementPrefab.gameObject, LogicElementLocation).GetComponent<LogicElementUI>();
        logicElement.Initialise(InventoryData.element, this,true);

        UpdateUI();
    }

    /// <summary>
    /// Called to check if this holder can hold the provided element;
    /// </summary>
    /// <param name="element">element to check if it can hold</param>
    /// <returns>returns true if this can hold the element </returns>
    public override bool canHold(LogicBlock element)
    {
        return element.isSameType(InventoryData.element);
    }

    /// <summary>
    /// Called when an element in this holder is double clicked
    /// </summary>
    /// <param name="element">element which was double clicked</param>
    public override void OnDoubleClick(LogicElementUI element)
    {

    }
    #endregion LogicElementHolder Implementation
}