using Godot;

namespace Cirno.Scripts.Components;

public partial class AlarmTrigger : Node2D
{
    private AlarmManager _alarmManager;
    
    [Export]
    public AlarmTriggerType TriggerType { get; private set; }

    [Export] public float ActivationRange { get; private set; } = 200f;
    
    [Export]
    public Node2D Target { get; private set; }
    
    [Export] public ActivationType ActivationType { get; private set; }

    public override void _Ready()
    {
        _alarmManager = this.GetAlarmManager(); //AlarmManager.Instance;
        if (TriggerType is AlarmTriggerType.OnEnabled)
        {
            _alarmManager.AlarmEnabled += AlarmManagerOnAlarmEnabled;
        }
        else
        {
            _alarmManager.AlarmDisabled += AlarmManagerOnAlarmDisabled;
        }
    }

    public override void _ExitTree()
    {
        _alarmManager.AlarmEnabled -= AlarmManagerOnAlarmEnabled;
        _alarmManager.AlarmDisabled -= AlarmManagerOnAlarmDisabled;
    }
    
    private void AlarmManagerOnAlarmDisabled()
    {
        Activate();
    }

    private void AlarmManagerOnAlarmEnabled(Vector2 location)
    {
        if (this.GlobalPosition.DistanceTo(location) <= ActivationRange)
        {
            Activate();
        }
    }

    private void Activate()
    {
        if (Target is IActivable activatable)
        {
            activatable.Activate(ActivationType);
        }
    }

    public enum AlarmTriggerType
    {
        OnEnabled,
        OnDisabled
    }
}

