extends Node2D

@onready var slots = $"../SlotArrays"
var selected_item: Node = null

func _input(event: InputEvent):
    if event.is_action_pressed("rmb"):
        if selected_item != null:
            remove_child(selected_item)
            selected_item = null
        slots.hide()

func _ready():
    for slot_array in slots.get_children():
        for slot in slot_array.get_children():
            slot.connect("clicked", _on_slot_clicked)
    slots.hide()
    
    # Starting carrots
    selected_item = preload("res://scene/entity/carrot.tscn").instantiate()
    $"../Economy".add(30)
    _on_slot_clicked(slots.get_child(0).get_child(2))
    _on_slot_clicked(slots.get_child(0).get_child(3))
    _on_slot_clicked(slots.get_child(0).get_child(4))
    selected_item = null

func _process(delta):
    if selected_item != null:
        selected_item.set_position(get_global_mouse_position())
        
func _on_slot_clicked(slot: Slot):
    if selected_item != null:
        if slot.plant == null:
            if $"../Economy".add(-selected_item.cost):
                var dup = selected_item.duplicate()
                slot.set_plant(dup)
                dup.set_process(true)
                dup.dead = false
                $"../Plants".add_child(dup)
                if dup is Mandrake:
                    $Coin.play()

func set_item(item: Node):
    if selected_item != null and selected_item.get_class() == item.get_class():
        remove_child(selected_item)
        selected_item = null
        slots.hide()
    else:
        if selected_item != null:
            remove_child(selected_item)
        selected_item = item
        slots.show()
        add_child(selected_item)
        selected_item.set_process(false)
        selected_item.dead = true
