extends PanelContainer

signal asset_updated()

@onready var refresh_button: Button = $MarginContainer/VBoxContainer/HBoxContainer/RefreshButton
@onready var item_list: ItemList = $MarginContainer/VBoxContainer/ItemList
@onready var search_line_edit: LineEdit = $MarginContainer/VBoxContainer/HBoxContainer/SearchLineEdit

var search_text = ""

func _ready() -> void:
	init_gui()

func _process(_delta: float) -> void:
	pass

func init_gui():
	visibility_changed.connect(_on_visibility_changed)
	
	refresh_button.pressed.connect(_on_refresh_button_pressed)
	search_line_edit.text_changed.connect(_on_search)
	item_list.set_drag_forwarding(_on_itemlist_get_drag_data, Callable(), Callable())
	
func update_data():
	if not AvatarDollDataMgr.initialed:
		return
	
	item_list.clear()
	item_list.add_item("__blank__", AvatarDollDataMgr.blank_texture)
	for asset_id in AvatarDollDataMgr.avatar_asset:
		var text = AvatarDollDataMgr.avatar_asset_name[asset_id]
		if search_text == "" or search_text in text:
			var icon = AvatarDollDataMgr.avatar_asset[asset_id]
			var index = item_list.add_item(text, icon)

func _on_visibility_changed():
	if is_visible_in_tree():
		update_data()

func _on_refresh_button_pressed():
	AvatarDollDataMgr.reload_all_asset()
	update_data()
	asset_updated.emit()

func _on_itemlist_get_drag_data(at_position: Vector2):
	var item_index = item_list.get_item_at_position(at_position)
	var asset_name = item_list.get_item_text(item_index)
	var icon = item_list.get_item_icon(item_index)
	
	var drag_preview = Control.new()
	var _size = icon.get_size()
	var _scale = 100.0 / max(_size.x, _size.y)
	
	var bg = ColorRect.new()
	bg.size = Vector2(100, 100)
	bg.position = Vector2(-50.0, -50.0)
	bg.color = Color(0.0, 0.675, 0.86, 0.5)
	drag_preview.add_child(bg)

	var texture = TextureRect.new()
	texture.texture = icon
	texture.scale = Vector2(_scale, _scale)
	texture.position = Vector2(-50.0, -50.0)
	drag_preview.add_child(texture)
	
	item_list.set_drag_preview(drag_preview) 
	var data = {
		"type": "asset_panel_drag",
		"data": {
			"asset_name": asset_name
		}
	}
	return data

func _on_search(new_text):
	search_text = new_text
	update_data()
