using System.Linq; 
using UnityEngine;
using UnityEngine.UI; 

public class SacrificeMenu : MonoBehaviour 
{
    public PressurePlate PressurePlate;
    public GameObject ItemSelectPrefab; 

    private RectTransform panelTransform;

    public void OnEnable()
    {
        Player.Instance.Inventory.OnSetItem += OnInventoryItemChanged;
        redraw(); 
    }

    public void OnDisable()
    {
        Player.Instance.Inventory.OnSetItem += OnInventoryItemChanged;
    }

    public void Awake()
    {
        this.panelTransform = this.GetComponent<RectTransform>(); 
    }

    public void OnInventoryItemChanged(int slot, int itemId)
    {
        redraw(); 
    }

    private void redraw()
    {
        foreach(Transform t in this.transform)
        {
            GameObject.Destroy(t.gameObject); 
        }

        Inventory i = Player.Instance.Inventory;

        int index = 0; 
        for (int n=0;n<i.Size; n++)
        {
            if(i.GetItem(n) != 0)
            {
                GameObject itemSelectObject = GameObject.Instantiate(ItemSelectPrefab);
                RectTransform t = itemSelectObject.GetComponent<RectTransform>();
                t.SetParent(this.transform, false);
                t.anchoredPosition = new Vector2(10, -10 - 110 * index);
                Button b = itemSelectObject.GetComponent<Button>();
                ItemSelectButton ib = itemSelectObject.GetComponent<ItemSelectButton>();
                ib.ItemImage.sprite = ItemManager.Instance.GetSprite(i.GetItem(n));
                ib.Slot = n;
                ib.SacrificeMenu = this;
                index++; 
            }
        }
        this.panelTransform.sizeDelta = new Vector2(300, 20 + index * 100 + Mathf.Clamp(index - 1, 0, int.MaxValue) * 10); 
    }

    public void OnItemPressed(int index)
    {
        Debug.Log("OnItemPressed " + index); 
        PressurePlate.SetItem(Player.Instance.Inventory.GetItem(index));
        Player.Instance.EquipItem(0, index); 
        this.gameObject.SetActive(false); 
    }

}