extends Control

@onready var portrait : AdventurerPortrait = $HeroPortrait

var option = 0
var opt_key : String = ""
var choices : Array = []
var appearance : Dictionary

signal portrait_customized()

func _ready() -> void:
	if Game.player_data.appearance.size() != 0:
		appearance = Game.player_data.appearance
	else:
		appearance = portrait.get_random_appearance()
	portrait.set_appearance(appearance)
	choices.resize(portrait.option_sets.size())
	choices.fill(0)
	opt_key = portrait.option_sets.keys()[option]
	portrait.flash_option(portrait.option_sets.keys()[option], true)

func _on_left_button_pressed() -> void:
	portrait.option_sets[opt_key].get_child(choices[option]).visible = false
	choices[option] -= 1
	if choices[option] < 0:
		choices[option] = portrait.option_sets[opt_key].get_child_count() - 1
	var node = portrait.option_sets[opt_key].get_child(choices[option])
	appearance[opt_key].type = node.name
	node.visible = true


func _on_right_button_pressed() -> void:
	portrait.option_sets[opt_key].get_child(choices[option]).visible = false
	choices[option] += 1
	if choices[option] >= portrait.option_sets[opt_key].get_child_count():
		choices[option] -= portrait.option_sets[opt_key].get_child_count()
	var node = portrait.option_sets[opt_key].get_child(choices[option])
	appearance[opt_key].type = node.name
	node.visible = true


func _on_up_button_pressed() -> void:
	portrait.flash_option(portrait.option_sets.keys()[option], false)
	option -= 1
	if option < 0:
		option = portrait.option_sets.keys().size() - 1
	opt_key = portrait.option_sets.keys()[option]
	portrait.flash_option(portrait.option_sets.keys()[option], true)


func _on_down_button_pressed() -> void:
	portrait.flash_option(portrait.option_sets.keys()[option], false)
	option += 1
	if option >= portrait.option_sets.keys().size():
		option -= portrait.option_sets.keys().size()
	opt_key = portrait.option_sets.keys()[option]
	portrait.flash_option(portrait.option_sets.keys()[option], true)
	

func _on_color_pressed(slot : ColorVariant.Types, col : String) -> void:
	var key : String
	match(slot):
		ColorVariant.Types.SKIN: key = "skin"
		ColorVariant.Types.HAIR: key = "hair"
		ColorVariant.Types.EYES: key = "eyes"
	appearance[key].color = col
	portrait.set_color(slot, col)


func _on_accept_button_pressed() -> void:
	portrait_customized.emit()


func _on_random_button_pressed() -> void:
	appearance = portrait.get_random_appearance()
	portrait.set_appearance(appearance)
