extends Control

signal goto_asset_using(using_type: String, asset_id: int, avatar_type: String, avatar_part_index: int, state_code: String, element_index: int)

@onready var asset_listview: Tree = $HSplitContainer/AssetPanel/MarginContainer/VBoxContainer/AssetListview
@onready var canvas_2d: Node2D = $HSplitContainer/HSplitContainer/PanelContainer2/SubViewportContainer/SubViewport/Canvas2d
@onready var use_listview: Tree = $HSplitContainer/HSplitContainer/PanelContainer/MarginContainer/VBoxContainer/UseListview

@onready var refresh_button: Button = $HSplitContainer/AssetPanel/MarginContainer/VBoxContainer/HBoxContainer/RefreshButton
@onready var add_button: Button = $HSplitContainer/AssetPanel/MarginContainer/VBoxContainer/HBoxContainer/AddButton
@onready var file_dialog: FileDialog = $FileDialog

@onready var file_name_line_edit: LineEdit = $HSplitContainer/HSplitContainer/PanelContainer/MarginContainer/VBoxContainer/GridContainer/FileNameLineEdit
@onready var file_path_line_edit: LineEdit = $HSplitContainer/HSplitContainer/PanelContainer/MarginContainer/VBoxContainer/GridContainer/FilePathLineEdit
@onready var image_size_line_edit: LineEdit = $HSplitContainer/HSplitContainer/PanelContainer/MarginContainer/VBoxContainer/GridContainer/ImageSizeLineEdit

var icon_checked: Texture2D = preload("res://Resources/UI/using.png")
var icon_missing_file: Texture2D = preload("res://Resources/UI/missing_file.png")
var icon_replace: Texture2D = preload("res://Resources/UI/replace.png")
var icon_delete: Texture2D = preload("res://Resources/UI/Trash.png")

var current_asset_id = -1

func _ready() -> void:
	init_gui()

func init_gui():
	get_tree().get_root().files_dropped.connect(_on_files_dropped)
	visibility_changed.connect(_on_visibility_changed)
	
	canvas_2d.set_editable(false)
	
	refresh_button.pressed.connect(_on_refresh_button_pressed)
	add_button.pressed.connect(_on_add_button_pressed)
	file_dialog.files_selected.connect(_on_file_dialog_files_selected)
	file_dialog.file_selected.connect(_on_file_dialog_file_selected)
	
	asset_listview.columns = 4
	asset_listview.hide_root = true
	asset_listview.set_column_custom_minimum_width(0, 16)
	asset_listview.set_column_custom_minimum_width(2, 16)
	asset_listview.set_column_custom_minimum_width(3, 16)
	asset_listview.set_column_expand(0, false)
	asset_listview.set_column_expand(1, true)
	asset_listview.set_column_expand(2, false)
	asset_listview.set_column_expand(3, false)
	asset_listview.item_selected.connect(_on_asset_listview_item_selected)
	#asset_listview.item_activated.connect(_on_asset_listview_item_activated)
	asset_listview.create_item()
	
	use_listview.columns = 4
	use_listview.set_column_title(0, "Type")
	use_listview.set_column_title(1, "Scope")
	use_listview.set_column_title(2, "Name")
	use_listview.set_column_title(3, "State")

	use_listview.set_column_custom_minimum_width(0, 65)
	use_listview.set_column_custom_minimum_width(1, 75)
	use_listview.set_column_custom_minimum_width(3, 75)
	use_listview.set_column_expand(0, false)
	use_listview.set_column_expand(1, false)
	use_listview.set_column_expand(2, true)
	use_listview.set_column_expand(3, false)
	use_listview.create_item()
	use_listview.item_activated.connect(_on_use_listview_item_activated)
	pass
	
func load_data():
	if not AvatarDollDataMgr.initialed:
		return
	
	asset_listview.clear()
	asset_listview.create_item() # root
	
	# asset_listview
	var assetMap = AvatarDollDataMgr.avatar_doll_data["AssetMap"]
	for asset_id in assetMap:
		if asset_id == 0:
			continue
		
		var asset_name = AvatarDollDataMgr.get_asset_name(asset_id)
		var item = asset_listview.create_item()
		item.set_cell_mode(0, TreeItem.CELL_MODE_ICON)
		item.set_cell_mode(2, TreeItem.CELL_MODE_ICON)
		item.set_text(1, asset_name)
		item.set_icon(3, icon_delete)
		
		item.set_metadata(0, asset_id)
		
		var asset_using = AvatarDollDataMgr.get_asset_using(asset_id)
		if asset_using.size() > 0:
			item.set_icon(0, icon_checked)
			
		if not FileAccess.file_exists(assetMap[asset_id][0]):
			item.set_icon(2, icon_missing_file)
		else:
			item.set_icon(2, icon_replace)
		
		if current_asset_id == asset_id:
			var use_sel = use_listview.get_selected()
			var state_code = null
			if use_sel:
				state_code = use_sel.get_text(3)
				
			asset_listview.set_selected(item, 0)
			
			for use_item in use_listview.get_root().get_children():
				if use_item.get_text(3) == state_code:
					use_listview.set_selected(use_item, 0)
					break
	
func update_data():
	# canvas_2d
	var asset_id =	current_asset_id
	if asset_id <= 0:
		canvas_2d.load_elements([])
		canvas_2d.queue_redraw()
		return
	
	var texture = AvatarDollDataMgr.get_asset(asset_id)
	var element = {
		"AssetId": asset_id,
		"Layer": 0,
		"LayerOffset": 0,
		"PositionX": 0,
		"PositionY": 0,
		"Rotation": 0,
		"ScaleX": 1.0,
		"ScaleY": 1.0,
		"Skew": 0,
	}
	canvas_2d.load_elements([element])
	canvas_2d.set_background(texture.get_size())
	canvas_2d.zoom_fit()
	canvas_2d.queue_redraw()
	# property
	file_name_line_edit.text = AvatarDollDataMgr.get_asset_name(asset_id)
	file_path_line_edit.text = AvatarDollDataMgr.avatar_doll_data["AssetMap"][asset_id][0]
	image_size_line_edit.text = "%d x %d" % [texture.get_size().x, texture.get_size().y]
	
	# using
	var asset_using = AvatarDollDataMgr.get_asset_using(asset_id)
	for using in asset_using:
		var new_item = use_listview.create_item()
		if using[0] == "icon":
			new_item.set_text(0, using[0]) # type
			new_item.set_text(1, using[1]) # scope
			new_item.set_text(2, AvatarDollDataMgr.avatar_doll_data[using[1]][using[2]]["Name"]) # name
			new_item.set_text(3, "") # state
		else:
			new_item.set_text(0, using[0]) # type
			new_item.set_text(1, using[1]) # scope
			new_item.set_text(2, AvatarDollDataMgr.avatar_doll_data[using[1]][using[2]]["Name"]) # name
			new_item.set_text(3, using[3]) # state
		
		new_item.set_metadata(0, using)
	pass
	
func _on_visibility_changed() -> void:
	if is_visible_in_tree() == true:
		load_data()

func _on_files_dropped(files):
	if not AvatarDollDataMgr.initialed:
		return
	
	var rect = asset_listview.get_global_transform() * asset_listview.get_rect()
	if rect.has_point(get_global_mouse_position()):
		for file_path in files:
			var asset_id = AvatarDollDataMgr.load_asset(file_path)
		load_data()
		
func _on_asset_listview_item_selected():
	use_listview.clear()
	use_listview.create_item() # root
	canvas_2d.load_elements([])
	
	var item = asset_listview.get_selected()
	if item == null:
		return
		
	current_asset_id = item.get_metadata(0)
	
	var column = asset_listview.get_column_at_position(asset_listview.get_local_mouse_position())
	if column == 2:
		var msg = "是否把 %s 替换为其他资源？" % AvatarDollDataMgr.get_asset_name(current_asset_id)
		var msg_box = MessageBox.question(self, 
			"提示", msg, 
			MessageBox.StandardButton.YES | MessageBox.StandardButton.NO)
		msg_box.accepted.connect(func(): 
			file_dialog.file_mode = FileDialog.FILE_MODE_OPEN_FILE
			file_dialog.show()
		)
	
	elif column == 3:
		var msg = "确定删除 %s 吗？\n所有相关引用也将被一并删除！" % AvatarDollDataMgr.get_asset_name(current_asset_id)
		var msg_box = MessageBox.warning(self, 
			"警告", msg, 
			MessageBox.StandardButton.YES | MessageBox.StandardButton.NO)
		msg_box.resize(Vector2(500, 150))

		msg_box.accepted.connect(func(): 
			AvatarDollDataMgr.remove_asset(current_asset_id)
			current_asset_id = -1
			load_data()
			update_data()
		)
		
	update_data()

func _on_use_listview_item_activated():
	var item = use_listview.get_selected()
	if item == null:
		return
	var using = item.get_metadata(0)
	if using[0] == "icon":
		goto_asset_using.emit(using[0], current_asset_id, using[1], using[2], "", -1)
	else:
		goto_asset_using.emit(using[0], current_asset_id, using[1], using[2], using[3], using[4])

func _on_refresh_button_pressed():
	AvatarDollDataMgr.reload_all_asset()
	load_data()
	update_data()

func _on_add_button_pressed():
	file_dialog.file_mode = FileDialog.FILE_MODE_OPEN_FILES
	file_dialog.show()

func _on_file_dialog_files_selected(files):
	for file_path in files:
		var asset_id = AvatarDollDataMgr.load_asset(file_path)
	load_data()

func _on_file_dialog_file_selected(file):
	AvatarDollDataMgr.replace_asset(current_asset_id, file)
	load_data()
	update_data()
	
	for item in asset_listview.get_root().get_children():
		if item.get_metadata(0) == current_asset_id:
			asset_listview.set_selected(item, 0)
			break
