extends PanelContainer

signal state_selected(state_code: String)

@onready var state_name_label: Label = $MarginContainer/VBoxContainer/HBoxContainer/StateNameLabel
@onready var combo_container: HBoxContainer = $MarginContainer/VBoxContainer/HBoxContainer2/ComboContainer
@onready var reset_button: Button = $MarginContainer/VBoxContainer/HBoxContainer2/ResetButton
@onready var icon_button: Button = $MarginContainer/VBoxContainer/HBoxContainer2/IconButton
@onready var list_button: Button = $MarginContainer/VBoxContainer/HBoxContainer2/ListButton
@onready var state_list: Tree = $MarginContainer/VBoxContainer/StateList
@onready var state_icon: ItemList = $MarginContainer/VBoxContainer/StateIcon

var _current_avatar_type = null
var _current_avatar_part = null
var state_comboboxes:Array[OptionButton] = []
var current_state: String
var combo_count = 0


func _ready() -> void:
	init_gui()

func init_gui():
	reset_button.pressed.connect(_on_reset_button_pressed)
	
	var button_group = ButtonGroup.new()
	icon_button.button_group = button_group
	list_button.button_group = button_group
	list_button.button_pressed = true
	state_icon.visible = false
	icon_button.pressed.connect(_on_icon_button_pressed)
	list_button.pressed.connect(_on_list_button_pressed)
	
	state_list.columns = 2
	state_list.hide_root = true
	state_list.column_titles_visible = true
	state_list.set_column_title(0, "Code")
	state_list.set_column_title(1, "Full Name")
	state_list.set_column_title_alignment(0, HORIZONTAL_ALIGNMENT_CENTER)
	state_list.set_column_title_alignment(1, HORIZONTAL_ALIGNMENT_LEFT)
	state_list.set_column_custom_minimum_width(0, 100)
	state_list.set_column_expand(0, false)
	state_list.set_column_expand(1, true)
	state_list.item_selected.connect(_on_state_list_item_selected)


func load_data(avatar_type, avatar_part = null):
	if avatar_type == null or avatar_part == null:
		for child in state_comboboxes:
			child.visible = false
		state_list.clear()
		state_list.create_item() # root
		return
	
	_current_avatar_type = avatar_type
	if avatar_part["Elements"].size() == 0:
		state_list.clear()
		state_list.create_item() # root
		return
	
	_current_avatar_part = avatar_part
	combo_count = avatar_part["Elements"].keys()[0].length()
	var state_set = {}
	for i in range(combo_count):
		state_set[i] = []
	
	# fill state_list, state_icon and collect state_set
	state_list.clear()
	state_list.create_item() # root
	state_icon.clear()
	
	var states = []
	for state_code in avatar_part["Elements"].keys():
		if avatar_part["Elements"][state_code].size() > 0:
			states.append(state_code)
	states.sort()
	
	for state_code in states:
		var state_names = AvatarDollDataMgr.get_state_names(avatar_type, state_code)
		var item = state_list.create_item()
		item.set_text(0, state_code)
		item.set_text(1, " / ".join(state_names))
		item.set_metadata(0, state_code)
		
		state_icon.add_item(state_code, AvatarDollDataMgr.default_texture)
		
		var index = -1
		for i in range(combo_count):
			index = AvatarDollDataMgr.get_state_index(state_code[i])
			if index != -1 and index not in state_set[i]:
				state_set[i].append(index)
	
	for i in state_set:
		state_set[i].sort()
		
	var part_state = AvatarDollDataMgr.avatar_part_state[avatar_type]
	var combo_content = {}
	for i in range(part_state.size()):
		var state = part_state[i]
		combo_content[i] = [ "All %s" % state["Name"]]
	
	for index in state_set:
		for i in state_set[index]:
			combo_content[index].append(part_state[index]["Values"][i])
		
	# create combo box
	if state_comboboxes.size() < combo_content.size():
		var sub = combo_content.size() - state_comboboxes.size()
		while sub > 0:
			var combo = OptionButton.new()
			combo.theme = preload("res://Resources/Theme/basic_theme.tres")
			combo.item_selected.connect(_on_state_combo_selected)
			state_comboboxes.append(combo)
			combo_container.add_child(combo)
			sub -= 1
	
	for index in range(state_comboboxes.size()):
		var combo = state_comboboxes[index]
		if index < combo_content.size():
			combo.visible = true
			combo.clear()
			for i in range(combo_content[index].size()):
				combo.add_item(combo_content[index][i])
				if i == 0:
					combo.set_item_metadata(i, "")
				else:
					var c = AvatarDollDataMgr.get_state_char(state_set[index][i - 1])
					combo.set_item_metadata(i, c)
		else:
			combo.visible = false
	pass

func update_filter():
	var state_vislble = {}
	var keys = _current_avatar_part["Elements"].keys()
	keys.sort()
	for state_code in keys:
		state_vislble[state_code] = true
	
	for i in range(combo_count):
		var combo = state_comboboxes[i]
		var c = combo.get_selected_metadata()
		if c == "":
			continue
		
		for state_code in state_vislble:
			if state_vislble[state_code] == false:
				continue
			if state_code[i] != c:
				state_vislble[state_code] = false
	
	for item in state_list.get_root().get_children():
		item.visible = state_vislble[item.get_metadata(0)]
	
	state_icon.clear()
	for state_code in state_vislble:
		if state_vislble[state_code]:
			state_icon.add_item(state_code, AvatarDollDataMgr.default_texture)

func _on_reset_button_pressed():
	for combo in state_comboboxes:
		combo.selected = 0
	update_filter()
	
func _on_icon_button_pressed():
	state_icon.visible = true
	state_list.visible = false
	
func _on_list_button_pressed():
	state_list.visible = true
	state_icon.visible = false
	
func _on_state_combo_selected(index):
	update_filter()

func _on_state_list_item_selected():
	var item = state_list.get_selected()
	if item != null: 
		var state_code = item.get_metadata(0)
		state_selected.emit(state_code)
		state_name_label.text = item.get_text(1)

func set_state_list_select(state_code):
	state_list.set_block_signals(true)
	if state_code == "":
		state_list.deselect_all()
	else:
		for item in state_list.get_root().get_children():
			if item.get_metadata(0) == state_code:
				state_list.set_selected(item, 0)
				state_name_label.text = item.get_text(1)
				break
	state_list.set_block_signals(false)
	
