﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class Inventory : MonoBehaviour
{
    /// <summary>
    /// A dictionary storing the type of item, and quantity available
    /// </summary>
    Dictionary<InventoryItem, int> items = new Dictionary<InventoryItem, int>();

    /// <summary>
    /// Add an item to the inventory
    /// </summary>
    /// <param name="item"></param>
    public void AddItem(InventoryItem item)
    {
        if (!items.ContainsKey(item))
            items[item] = 1;
        else
            items[item]++;
    }

    /// <summary>
    /// Count how many items of a particular type are in the inventory
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public int Count(InventoryItem item)
    {
        if (items.ContainsKey(item))
        {
            return items[item];
        }

        return 0;
    }

    private void OnGUI()
    {
        //lazy offset :(
        GUILayout.BeginArea(new Rect(400, 0, Screen.width - 400, Screen.height));

        //Get any item that has more than 0 available
        var availableItems = items.Where(x => x.Value > 0).ToList();

        //loop through them
        foreach (var pair in availableItems)
        {
            InventoryItem item = pair.Key;
            int quantity = pair.Value;

            //Spawn an item!
            if (GUILayout.Button($"{item.name} [{quantity}]"))
            {
                if (quantity > 0)
                {
                    //Spawn the prefab
                    Instantiate(pair.Key.prefab, transform.position, Quaternion.Euler(Random.insideUnitSphere * 50));
                    //decrement the item count
                    items[item]--;
                }
            }
        }
        GUILayout.EndArea();
    }
}
