extends Area2D

signal item_collected

export(String) var item_name = "undefined_item"
export(int) var item_quantity = 1

var is_valid = false
var map_icon: String

onready var inventory_ui  = get_tree().get_root().find_node("InventoryUI", true, false)

 
func _ready() -> void:

	
	is_valid = JSonData.item_data.has(item_name)
	
	if is_valid:
		map_icon = item_name + ".png"
		if JSonData.item_data[item_name].has("MapIcon"):
			map_icon = String(JSonData.item_data[item_name]["MapIcon"])
		elif JSonData.item_data[item_name].has("Icon"):
			map_icon = String(JSonData.item_data[item_name]["Icon"])
		
		if item_quantity <= 0:
			print ("CollectableItem.gd - Item Count must be 1 or higher, revert to 1")
			item_quantity = 1

	else:
		print ("CollectableItem.gd - Invalid item given: %s" % item_name)
		return
		

	if ResourceLoader.exists("res://data/images/items/" + map_icon):
		$Sprite.texture = load("res://data/images/items/" + map_icon)
	else:
		print ("collectableItem.gd - Missing icon image: %s" % item_name)
		
	#connect("item_collected", inventory_ui, "initialize_inventory")


func _on_CollectableItem_body_entered(body) -> void:
	var inventory_system = get_tree().get_nodes_in_group("InventorySystem")[0]
	var item_category = ""
	
	if JSonData.item_data[item_name].has("ItemCategory"):
		item_category = String(JSonData.item_data[item_name]["ItemCategory"])
		
	inventory_system.on_item_collected(item_name, item_category, item_quantity)

		
	emit_signal("item_collected")
	queue_free()
