extends AnimationPlayer
class_name Skill

@onready var character = (get_owner() as Character)
@onready var view = (%View as View)
@onready var status = (%Status as Status)
@onready var effect = (%Effect as Effect)

func init():
	cancel_skill()
	
func _process(delta):
	if status.is_skill_running and status.is_pause == is_playing():
		if status.is_pause:pause();
		else:play();
	
func cast_skill(cfg:SkillCfg,cast_dir:Vector2):
	break_skill()
	if cast_dir.length() == 0:
		cast_dir = Vector2.RIGHT if status.is_right else Vector2.LEFT
	if !cfg.free_lock and status.target:
		var target = Global.character_mgr.get_character(status.target)
		if target:
			cast_dir = character.pos2D().direction_to(target.pos2D()).normalized()
	
	var animation_name = "animation_library/%s" % Util.get_resource_name(cfg)
	if has_animation(animation_name):
		status.speed_up_rate = -1
		status.skill_move_speed = 0
		status.skill_float_speed = 0
		status.is_free_control = false
		status.is_free_turn = false
		status.is_skill_running = true
		status.skill_cfg = cfg
		status.skill_dir = cast_dir
		status.break_level = Enum.EBreakLevel.None
		status.skill_attack_index = 0
		status.skill_attack_effect_index = 0
		if cast_dir.x != 0: status.is_right = cast_dir.x > 0
		play(animation_name,-1,Setting.animation_speed_scale)
	else:
		print("技能animation不存在",animation_name)

func break_skill():
	stop()
	status.speed_up_rate = 0
	status.skill_move_speed = 0
	status.skill_float_speed = 0
	status.is_free_control = true
	status.is_free_turn = true
	status.is_skill_running = false
	status.skill_cfg = null
	status.break_level = Enum.EBreakLevel.Walk
	status.skill_attack_index = 0
	status.skill_attack_effect_index = 0
	effect.release_effect()

func cancel_skill():
	break_skill()
	view.reset()

func on_attack_miss():
	# 攻击未命中时跳帧
	advance(Setting.animation_frame_rate)

func _on_animation_finished(_anim_name):
	cancel_skill()
