using Cirno.Scripts.Resources;
using Godot;

namespace Cirno.Scripts.AttackPatterns;

public partial class AutonomousBulletEmitter : Node2D, IScriptHost
{
    public Node2D ParentObject => this;
    [Export]
    public BulletScript Script { get; set; }
    [Export]
    public bool EmitOnStart { get; set; } = false;
    
    [Signal] public delegate void DeathEventHandler();

    public double LifeTime { get; set; } = 0d;

    private double _lifeCounter = 0d;
    
    private bool _isActive = false;

    public bool Autonomous { get; set; } = true;
    
    protected BulletScript.BulletScriptMachine ScriptMachine;
    private Vector2 _homePosition;
    public Vector2 HomePosition => _homePosition;
    public void Start()
    {
        ScriptMachine = Script.Make(this);
        
        _homePosition = this.GlobalPosition;
        
        if (EmitOnStart)
        {
            _isActive = true;
            ScriptMachine.Start();
        }

    }

    public override void _Process(double delta)
    {
        if (!Autonomous) return;
        if (!_isActive) return;
        //this.GlobalPosition += new Vector2(10 * (float)delta, 0);
        Process(delta);
    }

    public void Update(double delta)
    {
        if (Autonomous) return;
        if (!_isActive) return;
        
        Process(delta);
    }

    private void Process(double delta)
    {
        _lifeCounter += delta;
        if (_lifeCounter >= LifeTime)
        {
            _isActive = false;
            EmitSignalDeath();
            QueueFree();
            return;
        }
        ScriptMachine.UpdatePhase(delta);
    }
    
    public void ChangeSpriteDirection(Vector2 direction)
    {
        
    }
    
}