extends Node

const IItem = preload("res://src/inventory/Items/IItem.gd")

#gui is the node where all inventory UI's get added into for now
var gui

var player_inventory: Inventory_Component
var equipment: Equipment_Component



func _ready():
	
	for node in get_tree().get_nodes_in_group("PlayerGUI"):
		gui = node
	player_inventory = playerData.inventory_component
	equipment = playerData.equipment_component



func _input(event):

	if event.is_action_pressed("inventory"):
		player_inventory.toggle_window(self)
		equipment.toggle_window(self)

	

func _create_item(item_name:String) -> IItem:
	var is_valid = JSonData.item_data.has(item_name)
	var item_image_name: String

	
	var item : IItem = IItem.new()
	
	item.i_name = item_name
	item.i_description = "Unknown item (" + item_name + ")"
	
	if is_valid:
		
		if JSonData.item_data[item_name].has("Icon"):
			item_image_name = String(JSonData.item_data[item_name]["Icon"])
		else:
			item_image_name = item_name + ".png"
		if ResourceLoader.exists("res://data/images/items/" + item_image_name):
			item.i_image = load("res://data/images/items/" + item_image_name)	
			
			
		if JSonData.item_data[item_name].has("Description"):
			item.i_description = String(JSonData.item_data[item_name]["Description"])
		else:
			item.i_description = item_name


		if JSonData.item_data[item_name].has("StackSize"):
			var stack_size = int(JSonData.item_data[item_name]["StackSize"])
			item.i_maxstack = stack_size
			if stack_size == 1:
				item.i_stackable = false
				
		if JSonData.item_data[item_name].has("Consumable"):
			item.i_consumable = true
		
		if JSonData.item_data[item_name].has("ItemCategory"):
			item.i_category = String(JSonData.item_data[item_name]["ItemCategory"])
			
		if JSonData.item_data[item_name].has("Damage"):
			item.i_damage = int(JSonData.item_data[item_name]["Damage"])
	return item
	
	
func add_to_inventory(inventory:Inventory_Component, item_name:String, amount:int):
	
	var item : IItem = _create_item(item_name)

	inventory.add_to_inventory(item, amount)
	



func on_item_collected(item_name:String, item_category:String, item_quantity:int):
	var item : IItem = _create_item(item_name)
	
	if equipment.has_slot_by_category(item_category) == false:
		player_inventory.add_to_inventory(item, item_quantity)
		
	else:
		if equipment.get_items_by_category(item_category)[0] == null:
			equipment.add_to_inventory(item, 1)
			for item_slot in get_tree().get_nodes_in_group("ItemSlot"):
				if item_slot.inv_comp_name == "Equipment":
					item_slot.refresh_slot()
		else:
			player_inventory.add_to_inventory(item, item_quantity)

