class_name ItemDetailsUI extends HBoxContainer

@export var equipment: Equipment
@export var viewport: SubViewport
@export var description_label: Label
@export var action_menu: Control

var current_item: Option = Option.none

var _displayed_item: Node3D
var _default_description: String

func _ready() -> void:
    action_menu.hide()
    _default_description = description_label.text

func _set_default():
    if _displayed_item != null:
        viewport.remove_child(_displayed_item)
        _displayed_item.queue_free()
    description_label.text = _default_description

func _on_updated(item: Option):
    current_item = item
    if item.is_some():
        var _item: Item = item.unwrap()
        match _item.create_preview():
            var x when x.is_some():
                _displayed_item = x.unwrap()
                viewport.add_child(_displayed_item)
            _: _set_default()
        description_label.text = _item.description
    else:
        _set_default()

func _on_selected(_item: Item):
    action_menu.show()

func _notification(what: int) -> void:
    if what == NOTIFICATION_FOCUS_EXIT:
        action_menu.hide()

func _is_equip(item: Item) -> bool:
    return is_instance_of(item, EquippableItem)

func _already_equipped(item: Item) -> bool:
    return equipment.is_equipped(item)

func use():
    if current_item.is_some():
        var item = current_item.unwrap()
        if _is_equip(item):
            if _already_equipped(item):
                equipment.unequip_item(item)
            else:
                equipment.equip(item)
        else:
            item.use()
    action_menu.hide()

func combine():
    current_item.inspect(func(x): x.combine())
    action_menu.hide()

func inspect():
    current_item.inspect(func(x): x.inspect())
    action_menu.hide()
