class_name AdventurerPortrait extends Control

var option_sets : Dictionary
var cv_lists : Array

func _ready() -> void:
	cv_lists = []
	cv_lists.resize(ColorVariant.Types.size())
	for i in range(len(cv_lists)):
		cv_lists[i] = []
	add_color_variants(get_children())
	for child : Control in get_children():
		if child.get_child_count() > 0:
			option_sets[child.name.to_lower()] = child

func add_color_variants(list : Array) -> void:
	for child : Control in list:
		if child is ColorVariant:
			cv_lists[child.type].append(child)
		if child.get_child_count() > 0:
			add_color_variants(child.get_children())


func set_appearance(appearance) -> void:
	set_color(ColorVariant.Types.HAIR, appearance.hair.color)
	#set_type(ColorVariant.Types.HAIR, appearance.hair.type)
	set_color(ColorVariant.Types.SKIN, appearance.skin.color)
	#set_color(ColorVariant.Types.SKIN, appearance.skin.type)
	set_color(ColorVariant.Types.EYES, appearance.eyes.color)
	#set_color(ColorVariant.Types.EYES, appearance.eyes.type)

func get_random_appearance() -> Dictionary:
	var app = {
		"hair":{
			"type":"",
			"color": random_color(ColorVariant.Types.HAIR)
		},
		"skin":{
			"type":"",
			"color": random_color(ColorVariant.Types.SKIN)
		},
		"eyes":{
			"type":"",
			"color": random_color(ColorVariant.Types.EYES)
		},
	}
	return app

static func random_color(type : ColorVariant.Types) -> String:
	var lst
	match(type):
		ColorVariant.Types.HAIR: lst = ColorVariant.hair_colors
		ColorVariant.Types.SKIN: lst = ColorVariant.skin_colors
		ColorVariant.Types.EYES: lst = ColorVariant.eye_colors
	var max = 0
	for opt in lst.keys():
		max += lst[opt].weight
	
	var pick = randi_range(1, max)
	for opt in lst.keys():
		if lst[opt].weight == 0: #Zero weighted colors are special options.
			continue
		pick -= lst[opt].weight
		if pick < 0:
			return opt
	return "ERROR"

func set_color(type : ColorVariant.Types, color : String) -> void:
	for cv : ColorVariant in cv_lists[type]:
		cv.set_color(color)

func flash_color_variants(node : Control, flashing : bool) -> void:
	if node is ColorVariant:
		node.flash(flashing)
	
	for child in node.get_children():
		flash_color_variants(child, flashing)
		
func flash_option(key : String, flashing : bool) -> void:
	flash_color_variants(option_sets[key], flashing)
