using Godot;

namespace Cirno.Scripts;

public partial class AlarmManager : Node2D
{
    [Export]
    public AudioStream AlarmSound { get; private set; }

    public static AlarmManager Instance { get; private set; }
    
    public bool IsAlarmOn { get; private set; } = false;
    
    public Vector2 LastAlarmPosition { get; private set; } = new Vector2();

    [Signal]
    public delegate void AlarmEnabledEventHandler(Vector2 location);
    
    [Signal]
    public delegate void AlarmDisabledEventHandler();

    private AudioStreamPlayer2D _player;

    public override void _Ready()
    {
        Instance = this;

        if (AlarmSound is not null) 
        {
            var player = new AudioStreamPlayer2D();
            player.Stream = AlarmSound;
            this.CallDeferred("add_child", player);

            _player = player;
        }
    }
    
    public void SoundAlarm(Vector2 location)
    {
        if (IsAlarmOn) return; 
        IsAlarmOn = true;
        LastAlarmPosition = location;
        EmitSignal(nameof(AlarmEnabled), location);
        
        GD.Print($"Alarm sounded at {location}");
        _player?.Play();
    }

    public void SoundSilentAlarm(Vector2 location)
    {
        if (IsAlarmOn) return; 
        EmitSignal(nameof(AlarmEnabled), location);
    }

    public void DisableAlarm()
    {
        IsAlarmOn = false;
        EmitSignal(nameof(AlarmDisabled));
        _player?.Stop();
    }
}