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


// item que nao gasta retorna false no delegate

public class Inventory : MonoBehaviour
{
    [SerializeField]
    int slotCount = 6;
    [SerializeField]
    float inventoryWidth = 0.1f;
    Item[] inventory;

    List<Item> database = new List<Item>();

    private void Start()
    {
        Control.inventory = this;
        inventory = new Item[slotCount];

        // fill database
        database.Add(new Item("Chave Antiga", "icon1", null));
        database.Add(new Item("Vaso", "icon1", null));
        database.Add(new Item("Chave Pequena", "icon1", null));
        database.Add(new Item("Semente", "icon1", null));
        database.Add(new Item("Rosa", "icon1", null));
        database.Add(new Item("Caixa de Ferramentas", "icon1", null));
    }

    private void OnGUI()
    {
        if (Dialog.manager.play) return;

        float slotsizey = Screen.height / slotCount;
        float yoffset = slotsizey / 20;
        float slotsizex = Screen.width * inventoryWidth;
        float xoffset = slotsizex / 20;
        float x = Screen.width - slotsizex;
  
        GUI.Box(new Rect(x, 0, slotsizex, Screen.height), "");
        var rect = new Rect(x + xoffset, yoffset, slotsizex - xoffset * 2, slotsizey - yoffset * 2);
        for (var i=0;i<slotCount;i++) {
            if (inventory[i] != null) {
                if (GUI.Button(rect, inventory[i].icon))
                    UseItem(i);
                rect.y += slotsizey;
            }
        }
    }
    
    public int CheckItem(string name)
    {
        for (var i = 0; i < inventory.Length; i++)
            if (inventory[i] != null) if (inventory[i].name == name) return i;
        return -1;
    }

    public void UseItem(string name)
    {
        UseItem(CheckItem(name));
    }
    public void UseItem(int id)
    {
        print(inventory[id].name + " used!");
        if (inventory[id].execute != null)
        {
            if(inventory[id].execute.Invoke(inventory[id].name))
                inventory[id] = null;
        }
    }

    // retorna false se nao tiver espaço
    public bool GetItem(string name)
    {
        for (var i = 0; i < slotCount; i++)
            if (inventory[i] == null)
                foreach(Item a in database)
                    if(a.name == name)
                    {
                        inventory[i] = a;
                        return true;
                    }
        print("no such item " + name);
        return false;
    }

    public delegate bool ItemDelegate(string n);
    
    class Item
    {
        public Item(string name, string texture, ItemDelegate method)
        {
            this.name = name;
            icon = Resources.Load(texture) as Texture2D;
            execute = method;
        }
        public string name;
        public Texture2D icon;
        public ItemDelegate execute;
    }


}
