class_name Equipment extends Resource

signal unequipped_primary(equipment: EquippableItem)
signal equipped_primary(equipment: EquippableItem)
signal unequipped_secondary(equipment: EquippableItem)
signal equipped_secondary(equipment: EquippableItem)

@export var _primary: EquippableItem

var primary: Option:
    get: return Option.from(_primary)
    set(value): set_primary(value)

func _unequip_primary():
    if _primary != null:
        var previous = _primary
        _primary = null
        unequipped_primary.emit(previous)

func _equip_primary(item: EquippableItem):
    if _primary != null:
        _unequip_primary()

    if item != null:
        _primary = item
        equipped_primary.emit(item)

func set_primary(item: Option):
    match item:
        var x when x.is_some():
            _equip_primary(x.unwrap())
        _: _unequip_primary()

@export var _secondary: EquippableItem

var secondary: Option:
    get: return Option.from(_secondary)
    set(value): set_secondary(value)

func _unequip_secondary():
    if _secondary != null:
        var previous = _secondary
        _secondary = null
        unequipped_secondary.emit(previous)

func _equip_secondary(item: EquippableItem):
    if _secondary != null:
        _unequip_secondary()

    if item != null:
        _secondary = item
        equipped_secondary.emit(item)

func set_secondary(item: Option):
    match item:
        var x when x.is_some():
            _equip_secondary(x.unwrap())
        _: _unequip_secondary()

func _init():
    call_deferred("_ready")

func _ready():
    if _primary != null:
        _equip_primary(_primary)

    if _secondary != null:
        _equip_secondary(_secondary)

func equip(item: EquippableItem):
    match item.type:
        EquippableItem.EquipmentType.PRIMARY: primary = Option.some(item)
        EquippableItem.EquipmentType.SECONDARY: secondary = Option.some(item)

func unequip(equip_type: EquippableItem.EquipmentType):
    match equip_type:
        EquippableItem.EquipmentType.PRIMARY: primary = Option.none
        EquippableItem.EquipmentType.SECONDARY:secondary = Option.none

func unequip_item(item: EquippableItem):
    equipped_to(item).inspect(unequip)

func is_equipped(item: EquippableItem) -> bool:
    return equipped_to(item).is_some()

func equipped_to(item: EquippableItem) -> Option:
    match item.type:
        EquippableItem.EquipmentType.PRIMARY when item == _primary: return Option.some(EquippableItem.EquipmentType.PRIMARY)
        EquippableItem.EquipmentType.SECONDARY when item == _secondary: return Option.some(EquippableItem.EquipmentType.SECONDARY)
    return Option.none
