extends Control

@onready var headbar_scene = preload("res://scene/ui/item/headbar.tscn")
@onready var camera: CameraManager = Global.camera_mgr

class HeadbarMeta:
	var pos:Vector3
	var headbar:Headbar

var headbar_map = {}

func _ready():
	SignalManager.character_create.connect(on_character_create)
	SignalManager.character_ui_pos_changed.connect(on_character_ui_pos_changed)
	SignalManager.character_destroy.connect(on_character_destroy)
	SignalManager.character_status_changed.connect(on_character_status_changed)
	SignalManager.character_hit_text.connect(on_character_hit_text)
	SignalManager.character_hit_damage.connect(on_character_hit_damage)
	SignalManager.character_die.connect(on_character_die)
	

func _process(delta):
	for k in headbar_map:
		var headbar_meta = headbar_map[k] as HeadbarMeta
		headbar_meta.headbar.position = camera.get_screen_pos(headbar_meta.pos)

func on_character_create(id:int,type:int,pos:Vector3):
	if type != Enum.ECharacterType.Monster:
		return
	var new_headbar_meta = HeadbarMeta.new()
	new_headbar_meta.pos = pos
	var new_headbar = headbar_scene.instantiate()
	add_child(new_headbar)
	new_headbar_meta.headbar = new_headbar
	on_character_ui_pos_changed(id,pos)
	headbar_map[id] = new_headbar_meta
	
func on_character_ui_pos_changed(id:int,pos:Vector3):
	if not id in headbar_map:
		return
	var headbar_meta = headbar_map[id]
	var headbar = headbar_meta.headbar as Headbar
	headbar_meta.pos = pos
	headbar.position = camera.get_screen_pos(pos)

func on_character_destroy(id:int):
	if not id in headbar_map:
		return
	var headbar_meta = headbar_map[id]
	var headbar = headbar_meta.headbar as Headbar
	headbar.queue_free()
	headbar_map.erase(id)

func on_character_status_changed(id:int,status_name:String,value):
	if not id in headbar_map:
		return
	var headbar_meta = headbar_map[id]
	var headbar = headbar_meta.headbar as Headbar
	var func_name = "on_%s_changed" % status_name
	if headbar.has_method(func_name):
		headbar.call(func_name,value)
	
func on_character_hit_text(id:int,value:String):
	if not id in headbar_map:
		return
	var headbar_meta = headbar_map[id]
	var headbar = headbar_meta.headbar as Headbar
	headbar.on_hit_text(value)

func on_character_hit_damage(id:int,value:float):
	if not id in headbar_map:
		return
	var headbar_meta = headbar_map[id]
	var headbar = headbar_meta.headbar as Headbar
	headbar.on_hit_damage(value)
	
func on_character_die(id:int):
	if not id in headbar_map:
		return
	var headbar_meta = headbar_map[id]
	var headbar = headbar_meta.headbar as Headbar
	headbar.queue_free()
	headbar_map.erase(id)
