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

public class InventoryManager : MonoBehaviour {

    public static List<Item> ItemRegister;
    public PlayerInventory PlayerInventory;
	void Start()
	{
		ItemRegister = GameManager.instance.itemRegister;
	}

    public bool CanCraft(string name)
    {
        foreach (Item item in ItemRegister)
        {
            if(item.Name == name)
            {
                if(!item.IsCraftable)
                {
                    return false;
                }

                if(item.Recipe.Count == 0)
                {
                    return true;
                }

                foreach (string ingredient in item.Recipe)
                {
                    string[] parts = ingredient.Split(':');
                    if(!PlayerInventory.HasItem(parts[0], int.Parse(parts[1]))) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }

    public void Craft(string name)
    {
        if (!CanCraft(name))
        {
            return;
        }

        foreach (Item item in ItemRegister)
        {
            if (item.Name == name)
            {
                if (item.Recipe.Count > 0)
                {
                    foreach (string ingredient in item.Recipe)
                    {
                        string[] parts = ingredient.Split(':');
                        PlayerInventory.RemoveItem(parts[0], int.Parse(parts[1]));
                    }
                    PlayerInventory.AddItem(item.Name, item.Stack);
                    return;
                }
                else
                {
                    return;
                }
            }
        }
    }
   
}
