class_name QuickSlots
extends Node


@export var highlight_theme: Resource

@onready var slots_container: GridContainer = $GridContainer

var _items: Array[String] = ["001", "005", "002", "003", "004", "006"]
var _previous_selected_item: int = 0
var _selected_item: int = 0 :
	set(new_item_index):
		if new_item_index < 0:
			new_item_index = _items.size() - 1
		elif new_item_index >= _items.size():
			new_item_index = 0
		_previous_selected_item = _selected_item
		_selected_item = new_item_index

func _init() -> void:
	InventoryManager.next_quick_slot.connect(select_next_item)
	InventoryManager.previous_quick_slot.connect(select_previous_item)
	InventoryManager.select_quick_slot.connect(select_quick_slot)

func _ready() -> void:
	var current_slot: Panel = slots_container.get_child(_selected_item)
	current_slot.set("theme_override_styles/panel", highlight_theme)

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("quickslot1"):
		select_quick_slot(0)
	elif event.is_action_pressed("quickslot2"):
		select_quick_slot(1)
	elif event.is_action_pressed("quickslot3"):
		select_quick_slot(2)
	elif event.is_action_pressed("quickslot4"):
		select_quick_slot(3)
	elif event.is_action_pressed("quickslot5"):
		select_quick_slot(4)
	elif event.is_action_pressed("quickslot6"):
		select_quick_slot(5)
	elif event.is_action_pressed("quickslot7"):
		select_quick_slot(6)
	elif event.is_action_pressed("quickslot8"):
		select_quick_slot(7)
	elif event.is_action_pressed("quickslot9"):
		select_quick_slot(8)
	elif event.is_action_pressed("quickslot10"):
		select_quick_slot(9)
	elif event.is_action_pressed("quickslot_next"):
		select_next_item()
	elif event.is_action_pressed("quickslot_previous"):
		select_previous_item()


func get_quickslot_index() -> int:
	return _selected_item

func get_selected_item() -> String:
	return _items[_selected_item]

func select_quick_slot(slot_index: int) -> void:
	_selected_item = slot_index
	update_highlighted_slot()
	InventoryManager.quick_slot_item_changed.emit(get_selected_item())

func select_previous_item() -> void:
	select_quick_slot(_selected_item + 1)

func select_next_item() -> void:
	select_quick_slot(_selected_item - 1)

func update_highlighted_slot() -> void:
	var previous_slot: Panel = slots_container.get_child(_previous_selected_item)
	var current_slot: Panel = slots_container.get_child(_selected_item)

	previous_slot.set("theme_override_styles/panel", null)
	current_slot.set("theme_override_styles/panel", highlight_theme)