using System;
using System.Collections.Generic;

public class Inventory
{
    public List<Item> items = new List<Item>();

    public int maxInventorySize = 8;
    public event EventHandler OnInventoryUpdate;

    public bool AddItem(Item item, int amount)
    {
        Item inventoryItem = items.Find(x => x.data.Id == item.data.Id && x.currentAmount + amount <= x.data.StackSize);
        if (inventoryItem != null)
        {
            inventoryItem.currentAmount += amount;
            NotifyInventoryChanged();
            return true;
        }

        if (items.Count < maxInventorySize)
        {
            items.Add(item);
            items[items.Count - 1].currentAmount += amount;
            NotifyInventoryChanged();
            return true;
        }

        return false;
    }

    public bool CanCraft(List<Ingredient> neededIngredients, int amount)
    {
        foreach (Ingredient ingredient in neededIngredients)
        {
            Item item = items.Find(x => x.data.Id == ingredient.Item && x.currentAmount >= ingredient.Amount * amount);
            if (item == null)
            {
                return false;
            }
        }

        return true;
    }

    public void RemoveItem(string id, int amount)
    {
        TryRemoveItem(id, amount);
    }

    public bool TryRemoveItem(string id, int amount)
    {
        if (GetItemAmount(id) < amount)
        {
            return false;
        }

        int remainingAmount = amount;
        for (int i = items.Count - 1; i >= 0 && remainingAmount > 0; i--)
        {
            Item item = items[i];
            if (item.data.Id != id) continue;

            int removedAmount = Math.Min(item.currentAmount, remainingAmount);
            item.currentAmount -= removedAmount;
            remainingAmount -= removedAmount;

            if (item.currentAmount <= 0)
            {
                items.RemoveAt(i);
            }
        }

        NotifyInventoryChanged();
        return true;
    }

    public int GetItemAmount(string id)
    {
        int amount = 0;
        foreach (Item item in items)
        {
            if (item.data.Id == id)
            {
                amount += item.currentAmount;
            }
        }

        return amount;
    }

    private void NotifyInventoryChanged()
    {
        OnInventoryUpdate?.Invoke(this, EventArgs.Empty);
    }
}
