extends Node3D
class_name CharacterManager

var character_map = {}
var character_idx : int = 0
var player_id : int

func _ready():
	Global.character_mgr = self
	SignalManager.level_loading_start.connect(on_level_loading_start)
	SignalManager.level_loading_end.connect(on_level_loading_end)

func on_level_loading_start():
	var player = get_player()
	if player:
		player.add_buff("freeze",-1)
		for enemy in get_enemy_list(player_id):
			SignalManager.character_die.emit(enemy.id())
			destroy_character(enemy.id())
	
func on_level_loading_end():
	var player = get_player()
	if player:player.remove_buff("freeze")
	
func create_character(cfg:CharacterCfg,team:Enum.ETeam,pos:Vector3)->Character:
	var characterNode:Node
	match cfg.type:
		Enum.ECharacterType.Player:characterNode = ResourceManager.scene_player.instantiate()
		Enum.ECharacterType.Monster:characterNode = ResourceManager.scene_monster.instantiate()
		Enum.ECharacterType.Bullet:characterNode = ResourceManager.scene_bullet.instantiate()
	add_child(characterNode)
	characterNode.name = cfg.name
	var character = characterNode as Character
	character_idx += 1
	character_map[character_idx]=character
	character.init(character_idx,cfg,team)
	character.set_material(ResourceManager.material_character.duplicate(),ResourceManager.material_character_sub.duplicate())
	character.set_pos(pos)
	SignalManager.character_create.emit(character_idx,cfg.type,character.ui_pos())
	if cfg.type == Enum.ECharacterType.Player:
		player_id = character_idx
	character.init_after()
	return character

func destroy_character(id:int):
	if not id in character_map:
		return
	var character_destroy = character_map[id] as Character
	character_destroy.queue_free()
	character_map.erase(id)
	for key in character_map:
		var character = character_map[key] as Character
		if character.target() == id:
			character.set_target(0)

func get_character(id:int) -> Character:
	if id in character_map:
		return character_map[id] as Character
	else:
		return null

func get_player() -> Character:return get_character(player_id)
func get_player_id() -> int:return player_id

func get_enemy_list(id:int) -> Array[Character]:
	var ret:Array[Character] = []
	var target = get_character(id)
	if !target:
		return ret
	for key in character_map:
		var character = character_map[key] as Character
		if character.team() != target.team():
			ret.append(character)
	return ret
