using System;
using Cirno.Scripts.AttackPatterns;
using Cirno.Scripts.Resources;
using Godot;

namespace Cirno.Scripts.Actors;

public partial class ScriptableBulletsEmitter : Node2D, IActivable, IScriptHost
{
    public Node2D ParentObject => this;

    [Export]
    public BulletScript Script { get; set; }

    [Export]
    public bool InvertSignal { get; private set; } = false;
    
    [Export]
    public bool EmitOnStart { get; set; } = false;
    
    [Signal]
    public delegate void StateChangedEventHandler(bool isEmitting);

    private bool _isActive = false;

    //private BulletScript _scriptInstance;

    protected BulletScript.BulletScriptMachine ScriptMachine; 
    
    public override void _Ready()
    {
        //_scriptInstance = Script.Duplicate(true) as BulletScript;

        ScriptMachine = Script.Make(this);
        
        _homePosition = this.GlobalPosition;
        
        if (EmitOnStart)
        {
            _isActive = true;
            ScriptMachine.Start();
        }
        EmitSignal(SignalName.StateChanged, _isActive);
    }

    public bool Activate(ActivationType activationType = ActivationType.Toggle)
    {
        switch (activationType)
        {
            case ActivationType.Use:
            case ActivationType.Toggle:
                _isActive = !_isActive;
                break;
            case ActivationType.Open:
            case ActivationType.Enable:
                _isActive = !InvertSignal;
                break;
            case ActivationType.Close:
            case ActivationType.Disable:
                _isActive = InvertSignal;
                break;
            case ActivationType.Destroy:
                _isActive = InvertSignal;
                // TODO: Explode
                break;
        }

        if (_isActive)
        {
            ScriptMachine.Start();
        }
        
        EmitSignal(SignalName.StateChanged, _isActive);

        return true;
    }
    
    public override void _Process(double delta)
    {
        if (!_isActive) return;
        
        ScriptMachine.UpdatePhase(delta);
    }

    private Vector2 _homePosition;
    public Vector2 HomePosition => _homePosition;
    
    public void ChangeSpriteDirection(Vector2 direction)
    {
        
    }
}