using Cirno.Scripts.Enums;
using Godot;

namespace Cirno.Scripts.Components.FSM.Enemy;

public partial class EnemyAlarmModule : ModuleBase<EnemyState, CharacterBody2D>
{
    private IStateMachine<EnemyState, CharacterBody2D> _machine;
    
    [Export]
    public PlayerDetectionModule PlayerDetection { get; private set; }

    private bool _enabled = false;
    
    public override void EnterState(EnemyState state)
    {
        _enabled = true;
        CallDeferred(MethodName.AssignAlarmManagerDeferred);
    }

    public override void ExitState(EnemyState state)
    {
        _enabled = false;
        AlarmManager.Instance.AlarmEnabled -= InstanceOnAlarmEnabled;
    }

    private void AssignAlarmManagerDeferred()
    {
        AlarmManager.Instance.AlarmEnabled += InstanceOnAlarmEnabled;
    }

    public override void Init(IStateMachine<EnemyState, CharacterBody2D> machine)
    {
        _machine = machine;
        // if (AlarmManager.Instance is not null)
        // {
        //     AlarmManager.Instance.AlarmEnabled += InstanceOnAlarmEnabled;
        // }
        // else
        // {
        //     GD.Print("Alarm Manager is null");
        // }
    }

    private void InstanceOnAlarmEnabled(Vector2 location)
    {
        if (_enabled)
        {
            PlayerDetection.LastKnownPlayerPosition = location;
            _machine.SetState(EnemyState.Alert);
        }
        
    }

    public override void Process(double delta)
    {
        
    }

    public override void PhysicsProcess(double delta)
    {
        
    }
}