extends PanelContainer

@onready var state_treeview: Tree = $HSplitContainer/VSplitContainer/PanelContainer/MarginContainer/VBoxContainer/AvatarStateTreeview
@onready var state_add_button: Button = $HSplitContainer/VSplitContainer/PanelContainer/MarginContainer/VBoxContainer/HBoxContainer/Add
@onready var state_del_button: Button = $HSplitContainer/VSplitContainer/PanelContainer/MarginContainer/VBoxContainer/HBoxContainer/Del
@onready var total_state_treeview: Tree = $HSplitContainer/VSplitContainer/PanelContainer2/MarginContainer/VBoxContainer/TotalStateTreeview

@onready var button_0: Button = $HSplitContainer/PanelContainer/MarginContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer/Button0
@onready var button_1: Button = $HSplitContainer/PanelContainer/MarginContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer/Button1
@onready var button_2: Button = $HSplitContainer/PanelContainer/MarginContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer/Button2
@onready var button_3: Button = $HSplitContainer/PanelContainer/MarginContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer/Button3
@onready var button_4: Button = $HSplitContainer/PanelContainer/MarginContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer/Button4
@onready var slot_check_box: CheckBox = $HSplitContainer/PanelContainer/MarginContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer3/SlotCheckBox
@onready var value_treeview: Tree = $HSplitContainer/PanelContainer/MarginContainer/HBoxContainer/MarginContainer/VBoxContainer/HBoxContainer2/ValueTreeview

var states_index = -1
var scope_buttons = []
var current_scope = 0
var states = null

func _ready() -> void:
	_init_gui()

func _init_gui():
	visibility_changed.connect(_on_visibility_changed)
	
	# avatar_state
	state_treeview.columns = 3
	state_treeview.hide_root = true
	state_treeview.set_column_title(0, "ID")
	state_treeview.set_column_title(1, "Name")
	state_treeview.set_column_title(2, "State")
	state_treeview.set_column_custom_minimum_width(0, 40)
	state_treeview.set_column_custom_minimum_width(2, 40)
	state_treeview.set_column_expand(1, true)
	state_treeview.set_column_expand_ratio(1, 4)
	state_treeview.item_selected.connect(_on_avatar_state_treeview_selected)
	#state_treeview.nothing_selected.connect(_on_asset_listview_nothing_selected)
	
	# total_state_treeview
	total_state_treeview.columns = 3
	total_state_treeview.hide_root = true
	total_state_treeview.set_column_title(0, "Part")
	total_state_treeview.set_column_title(1, "Required")
	total_state_treeview.set_column_title(2, "Max")
	total_state_treeview.create_item()
	
	# scope_buttons
	scope_buttons.append(button_0)
	scope_buttons.append(button_1)
	scope_buttons.append(button_2)
	scope_buttons.append(button_3)
	scope_buttons.append(button_4)
	for i in range(scope_buttons.size()):
		var btn = scope_buttons[i]
		btn.toggled.connect(_on_scope_button_pressed.bind(i))
	pass
	
	slot_check_box.toggled.connect(_onslot_check_box_toggled)
	
	# value_treeview
	value_treeview.columns = 3
	value_treeview.hide_root = true
	value_treeview.set_column_title(0, "ID")
	value_treeview.set_column_title(1, "Value")
	value_treeview.set_column_title(2, "Required")
	value_treeview.set_column_custom_minimum_width(0, 40)
	value_treeview.set_column_custom_minimum_width(2, 60)
	value_treeview.set_column_expand(0, false)
	value_treeview.set_column_expand(1, true)
	value_treeview.set_column_expand(2, false)
	value_treeview.item_edited.connect(_on_value_treeview_item_edited)
	var root = value_treeview.create_item()
	root.set_cell_mode(2, TreeItem.CELL_MODE_CHECK)
	root.set_checked(2, false)

func load_data():
	if AvatarDollDataMgr.initialed == false:
		return
		
	states = AvatarDollDataMgr.avatar_doll_data["Settings"]["States"]
	
	state_treeview.clear()
	state_treeview.create_item() # root

	value_treeview.clear()
	value_treeview.create_item()
	
	# state_treeview
	for i in range(states.size()):
		var state = states[i]
		var item = state_treeview.create_item()
		item.set_text(0, str(i))
		item.set_text(1, str(state["Name"]))
		item.set_text(2, str(state["Values"].size()))
		item.set_text_alignment(0, HORIZONTAL_ALIGNMENT_CENTER)
		item.set_text_alignment(1, HORIZONTAL_ALIGNMENT_CENTER)
		item.set_text_alignment(2, HORIZONTAL_ALIGNMENT_CENTER)
			
	# total_state_treeview
	update_total_state()
	
	if states.size() > 0:
		state_treeview.set_selected(state_treeview.get_root().get_child(0), 0)

func _on_visibility_changed() -> void:
	if is_visible_in_tree() == true:
		load_data()

func _on_scope_button_pressed(_toggled_on, _index):
	if not AvatarDollDataMgr.initialed:
		return
		
	current_scope = 0
	for i in range(scope_buttons.size()):
		if scope_buttons[i].button_pressed:
			current_scope += 1 << i
	states[states_index]["Scope"] = current_scope
	update_total_state()

func _onslot_check_box_toggled(toggled_on):
	if not AvatarDollDataMgr.initialed or states_index < 0:
		return
	states[states_index]["Slot"] = toggled_on
	update_total_state()

func _on_avatar_state_treeview_selected():
	if not AvatarDollDataMgr.initialed:
		return
		
	value_treeview.clear()
	value_treeview.create_item() # root
	
	states_index = int(state_treeview.get_selected().get_text(0))
	if states_index < 0:
		for i in range(5):
			scope_buttons[i].set_pressed_no_signal(false)
		return
		
	var state = states[states_index]
	var scope = int(state["Scope"])
	for i in range(5):
		var s = scope & 1
		scope_buttons[i].set_pressed_no_signal(s == 1)
		scope = scope >> 1
		
	slot_check_box.set_pressed_no_signal(state["Slot"])
		
	for i in range(state["Values"].size()):
		var item = value_treeview.create_item()
		item.set_text_alignment(0, HORIZONTAL_ALIGNMENT_CENTER)
		item.set_text_alignment(1, HORIZONTAL_ALIGNMENT_CENTER)
		item.set_cell_mode(2, TreeItem.CELL_MODE_CHECK)
		item.set_editable(1, true)
		item.set_editable(2, true)
		
		item.set_text(0, str(i))
		item.set_text(1, state["Values"][i])
		item.set_checked(2, state["Required"][i])
		
func _on_value_treeview_item_edited():
	if not AvatarDollDataMgr.initialed or states_index < 0:
		return
		
	var item = value_treeview.get_edited()
	var row = int(item.get_text(0))
	var column = value_treeview.get_edited_column()
	var state = states[states_index]
	
	if column == 1: state["Values"][row] = item.get_text(column)
	elif column == 2: state["Required"][row] = item.is_checked(column)
	
	update_total_state()
	
func update_total_state():
	total_state_treeview.clear()
	total_state_treeview.create_item()
	
	var slot_required = 0
	var slot_max = 0
	
	var total_state_required = [0, 0, 0, 0, 0]
	var total_state_max = [0, 0, 0, 0, 0]
	for state in states:
		var required = 0
		var value_count = state["Values"].size()
		for r in state["Required"]:
			if r: required += 1
		
		if state["Slot"]:
			if slot_required == 0:
				slot_required = value_count
			else:
				slot_required *= value_count
				
			if slot_max == 0:
				slot_max = value_count
			else:
				slot_max *= value_count
		
		var scope = int(state["Scope"])
		for i in range(5):
			if scope & 1 == 1:
				if total_state_max[i] == 0:
					total_state_max[i] = value_count
				else:
					total_state_max[i] *= value_count
				
				if total_state_required[i] == 0:
					total_state_required[i] = required
				else:
					total_state_required[i] *= required
					
			scope = scope >> 1
	
	slot_required = slot_required if slot_required != 0 else 1
	slot_max = slot_max if slot_max != 0 else 1
	
	# set data
	var item = total_state_treeview.create_item()
	item.set_text(0, "Slot")
	item.set_text(1, str(slot_required))
	item.set_text(2, str(slot_max))
	item.set_text_alignment(0, HORIZONTAL_ALIGNMENT_CENTER)
	item.set_text_alignment(1, HORIZONTAL_ALIGNMENT_CENTER)
	item.set_text_alignment(2, HORIZONTAL_ALIGNMENT_CENTER)
	
	var parts = ["Body", "Head", "Hair", "Face", "Cloth"]
	for i in range(5):
		item = total_state_treeview.create_item()
		item.set_text(0, parts[i])
		item.set_text(1, str(total_state_required[i]))
		item.set_text(2, str(total_state_max[i]))
		item.set_text_alignment(0, HORIZONTAL_ALIGNMENT_CENTER)
		item.set_text_alignment(1, HORIZONTAL_ALIGNMENT_CENTER)
		item.set_text_alignment(2, HORIZONTAL_ALIGNMENT_CENTER)
