using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; 

public class InventoryRenderer : MonoBehaviour {
    public GameObject InventorySlotRendererPrefab; 

    private InventorySlotRenderer[] inventorySlotRenderers;
    private RectTransform rectTransform;

    private Inventory inventory; 

    public void Start()
    {
        this.rectTransform = this.GetComponent<RectTransform>(); 
    }

    public void OnDisable()
    {
        if(inventory != null)
        {
            inventory.OnSetItem -= this.OnInventoryItemSet; 
        }
    }

    public void OnEnable()
    {
        if(inventory != null) 
        {
            inventory.OnSetItem += this.OnInventoryItemSet;
        }
    }

    public void SetInventory(Inventory inventory)
    {
        inventorySlotRenderers = new InventorySlotRenderer[inventory.Size]; 
        rectTransform.sizeDelta = new Vector3(inventory.Size * 100, 100); 
        for(int n=0;n< inventory.Size; n++)
        {
            InventorySlotRenderer slot = (GameObject.Instantiate(InventorySlotRendererPrefab)).GetComponent<InventorySlotRenderer>();
            inventorySlotRenderers[n] = slot;
            slot.gameObject.transform.SetParent(this.transform, false); 
            inventorySlotRenderers[n].SetIndex(n); 
        }
        inventory.OnSetItem += this.OnInventoryItemSet; 
    }

    private void OnInventoryItemSet(int slot, int itemId)
    {
        Debug.Log("OnInventoryItemSet " + slot + " " + itemId); 
        inventorySlotRenderers[slot].SetItem(itemId); 
    }

}
