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

public class Inventory : MonoBehaviour {

    public List<Item> InventoryItems;
    public int WeightLimit = 100;
    public int SlotCount = 10;

    GameObject gui;

    // Use this for initialization
    public virtual void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    public virtual void TriggerInventoryPanel(bool crafting)
    {
        
    }

    public void CloseInventory()
    {
        Destroy(gui);
    }

    public int AddItem(string name, int count = 1)
    {
        int left = count;
        foreach (Item item in InventoryItems)
        {
            if(item.Name == name)
            {
                for(int i = 0; i < count; i++)
                {
                    if(HasPlace(item.Weight))
                    {
                        item.Stack += 1;
                        left--;
                    }
                }
                return left;
            }
        }

        foreach (Item item in InventoryManager.ItemRegister)
        {
            if(item.Name == name)
            {
                Item i = Instantiate(item);
                i.Stack = 0;
                for (int j = 0; j < count; j++)
                {
                    if (HasPlace(i.Weight))
                    {
                        i.Stack += 1;
                        left--;
                    }
                }
                InventoryItems.Add(i);
                return left;
            }
        }

        return left;
    }

    public void RemoveItem(string name, int count = 1)
    {
        List<Item> items = new List<Item>();
        foreach(Item item in InventoryItems)
        {
            if(item.Name == name)
            {
                item.Stack = Mathf.Min(item.Stack, count);
            }
            if(item.Stack > 0)
            {
                items.Add(item);
            }
        }
        InventoryItems = items;
    }

    public bool HasItem(string name, int count = 1)
    {
        foreach (Item item in InventoryItems)
        {
            if(name == item.Name && count <= item.Stack)
            {
                return true;
            }
        }
        return false;
    }

    public bool HasPlace(int neededWeight)
    {
        int weight = 0;
        foreach (Item item in InventoryItems)
        {
            weight += item.Weight * item.Stack;
        }

        return WeightLimit - weight >= neededWeight;
    }

}
