# A manager for inventory objects
extends Resource
class_name ESCItemCountManager


func add(global_id: String, value:= 1) -> void:
	var item = get_item(global_id)
	set(global_id, item.count + value)


func remove(global_id: String, value:= 1) -> void:
	var item = get_item(global_id)
	set(global_id, item.count - value)


func set(global_id: String, value: int) -> void:
	var item = get_item(global_id)
	item.count = value
	escoria.globals_manager.set_global("count/%s" % global_id, value)
	updateSprite(item)


func removeFromInventoryIfCountLessThan(global_id: String, value:= 1) -> void:
	var item = get_item(global_id)
	if item.count < value:
		escoria.inventory_manager.remove_item(global_id)


func get_item(global_id: String) -> ESCItem:
	var node = escoria.object_manager.get_object(global_id).node
	if not node is ESCItem:
		escoria.logger.error(
		  "item_count_add: invalid object",
		  ["Object is not an ESCItem"]
		)
		return null

	return node


func updateSprite(item: ESCItemWithTooltip) -> void:
	var child_node = item.get_node("Sprite") as Sprite
	if not child_node is Sprite:
		escoria.logger.error(
			self,
			"No Sprite node found"
		)
  
	var texture_path = getCountTexturePath(item)
	var texture = load(texture_path)

	# Update texture in scene
	var sprite = child_node as Sprite
	sprite.texture = texture

	# Update texture in scene
	# TODO optional inventory_texture
	# TODO change inventory texture without removing and adding the item
	# https://github.com/godot-escoria/escoria-issues/issues/364
	# https://discord.com/channels/884336424780984330/1124614097917460584/1127151969614696548
	item.inventory_texture = texture
	if escoria.inventory_manager.inventory_has(item.global_id):
		escoria.inventory_manager.remove_item(item.global_id)
		escoria.inventory_manager.add_item(item.global_id)


func getCountTexturePath(item: ESCItemWithTooltip) -> String:
	var count = item.count
	var textures = item.count_textures # TODO sort dictionaries by start key
	var i = 0

	while (i < textures.size() - 1) and count >= textures[i + 1].start:
		i = i + 1

	return textures[i].texture
