extends Node3D
class_name Effect

@onready var afterimage = preload("res://scene/effect/afterimage/normal.tscn")
@onready var corpse = preload("res://scene/effect/afterimage/normal.tscn")
@onready var readiness_hero = preload("res://scene/effect/readiness/readiness_hero.tscn")
@onready var readiness_monster = preload("res://scene/effect/readiness/readiness_monster.tscn")
@onready var readiness_bullet = preload("res://scene/effect/readiness/readiness_bullet.tscn")

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

var rediness : Decal
var is_pause : bool
var is_right : bool

func init(type:Enum.ECharacterType,body_scale:Vector3):
	match type:
		Enum.ECharacterType.Player:rediness = readiness_hero.instantiate()
		Enum.ECharacterType.Monster:rediness = readiness_monster.instantiate()
		Enum.ECharacterType.Bullet:rediness = readiness_bullet.instantiate()
	if rediness:
		rediness.scale = body_scale *2.2
		rediness.scale.y = 10
		rediness.position = Vector3.DOWN * 4
		add_child(rediness)

func _process(delta):
	#指针方向
	if status.move_dir:
		var angle = status.move_dir.angle_to(Vector2.RIGHT)
		rediness.rotation.y = angle
	#flip
	if is_right != status.is_right:
		is_right = status.is_right
		for child in get_children():
			if child is Particle:
				child.scale.x = 1 if is_right else -1
	#pause
	if is_pause != status.is_pause:
		is_pause = status.is_pause
		for child in get_children():
			if child is Particle:
				var particle = child as Particle
				particle.set_pause(is_pause)

func cast_image(res:Resource):
	var new_afterimage = afterimage.instantiate() as Afterimage
	new_afterimage.position = character.view_pos()
	new_afterimage.name = "afterimage"
	new_afterimage.velocity = character.velocity / 4
	new_afterimage.target = view
	SignalManager.effect_create.emit(new_afterimage)
	
func cast_after_image():cast_image(afterimage)
func cast_corpse():cast_image(corpse)
func cast_attack_particle():
	if !status.skill_cfg:
		return
	var attack_particle = status.skill_cfg.get_attack_particle(status.skill_attack_effect_index)
	status.skill_attack_effect_index += 1
	if !attack_particle:
		print("未配置技能攻击特效:",status.skill_cfg.resource_path)
		return
	cast_particle(attack_particle)

func cast_particle(resource:Resource):
	if !resource:
		print("未配置技能特效")
		return
	var new_particle = resource.instantiate() as Particle
	new_particle.position = status.basic_offset
	new_particle.name = "particle"
	var dir = status.skill_dir as Vector2
	dir.x = abs(dir.x)
	var angle = dir.angle_to(Vector2.RIGHT)
	new_particle.rotation.y = angle if is_right else -angle
	new_particle.scale.x = abs(new_particle.scale.x) * (1 if is_right else -1)
	add_child(new_particle)

func release_effect():
	for child in get_children():
		if child is Particle:
			var particle = child as Particle
			particle.position = character.view_pos()
			remove_child(particle)
			SignalManager.effect_create.emit(particle)

