class_name InventoryUI extends Control

@export var inventory: Inventory
@export var item_scene: PackedScene
@export var carousel: Carousel

func _ready() -> void:
	inventory.updated.connect(_build_carousel)

func _build_carousel():
	KCUtils.remove_children(carousel)

	var items = inventory.items.values()
	var count = items.size()
	for i in range(inventory.max_capacity):
		var scene = create_item()
		var value = Option.none
		if i < count:
			value = Option.some(items[i].item)
		bind_item(scene, value)
		carousel.add_child(scene)

func create_item() -> Node:
	return item_scene.instantiate()

func bind_item(node: Node, item: Option):
	if node.has_method('bind'):
		node.bind(item)

func _gui_input(event: InputEvent) -> void:
	if event.is_action_pressed(PlayerInput.UIAction.Right):
		move_right()
	elif event.is_action_pressed(PlayerInput.UIAction.Left):
		move_left()

func move_by(delta: int):
	var next_index = carousel.get_carousel_index() + delta
	carousel.go_to_index(next_index)

func move_right():
	move_by(1)

func move_left():
	move_by(-1)
