using Cirno.Scripts.Resources;
using Godot;

namespace Cirno.Scripts.Components.Actors;

public partial class DeathAnimationHandler : ActorModule 
{
    protected Actor _actor;
    
    [Export] public BulletResource ExplosionData { get; set; }
    [Export] public PackedScene ExplosionParticles { get; set; }
    [Export] public PackedScene DebrisScene { get; set; }
    
    public override void Init(Actor actor)
    {
        _actor = actor;
        _actor.OnDeath += ParentOnOnDeath;
    }
    
    protected virtual void ParentOnOnDeath()
    {
        CreateExplosion();
        CreateParticles();
        CreateDebris();
        
        _actor.QueueFree();
    }

    public override void Update(double delta)
    {
        
    }

    public override void PhysicsUpdate(double delta)
    {
        
    }
    
    private void CreateExplosion() 
    {
        if (ExplosionData == null) return;

        var explosion = _actor.CreateSibling<Bullet>(ExplosionData.BulletScene);
        explosion.Speed = 0;
		
        explosion.Initialize(ExplosionData.MakeBullet(_actor.GlobalPosition), GameManager.Instance);
    }
    
    private void CreateParticles()
    {
        if (ExplosionParticles == null) {
            return;
        }
        var particle = _actor.CreateSibling<GpuParticles2D>(ExplosionParticles);
        if (particle == null) return;

        particle.Emitting = true;
    }
    
    private void CreateDebris()
    {
        if (DebrisScene == null) return;
        _actor.CreateSibling<Node2D>(DebrisScene);
    }
}