@tool
extends Node3D

const MUTATION_DISCOVERY_ELEMENT_SCENE = preload("res://stages/3d_scenes/cockpit_scene/cockpit_elements/mutation_discovered_screen/mutation_discovery_element.tscn")

@export var all_mutations: Array[PlantMutation]
@export var mutations_unlocked: int
@export var planted_mutation_ids: Array[String]

@export_tool_button("Update", "Callable") var update_action = update

# Called when the node enters the scene tree for the first time.
func _ready():
    if not Engine.is_editor_hint():
        all_mutations = GameInfo.game_data.progression_data.get_all_mutations()
        mutations_unlocked = len(GameInfo.game_data.progression_data.get_available_mutations())
        planted_mutation_ids = GameInfo.game_data.progression_data.get_mutations_discovered()
    update()

func update():
    if is_node_ready():
        for c in %Icons.get_children():
            c.queue_free()
        var n_mutation := len(all_mutations)
        var offset := .09
        var n_columns := 8
        var n_expected_rows := floori(float(n_mutation) / n_columns) + 1
        var n_missing_mutation = n_expected_rows * n_columns - n_mutation
        for i in range(n_mutation):
            var el := MUTATION_DISCOVERY_ELEMENT_SCENE.instantiate() as MutationDiscoveryElement
            if i < mutations_unlocked:
                el.mutation = all_mutations[i]
                if el.mutation.get_mutation_id() in planted_mutation_ids:
                    el.state = MutationDiscoveryElement.State.DISCOVERED
                else:
                    el.state = MutationDiscoveryElement.State.UNDISCOVERED
            else:
                el.state = MutationDiscoveryElement.State.LOCKED
            %Icons.add_child(el)
            var row_ind := floori(float(i) / n_columns)
            el.position.y = - offset * row_ind
            el.position.z = - (i % n_columns) * offset
            if row_ind == n_expected_rows - 1:
                el.position.z -= .5 * offset * n_missing_mutation
