using Godot;

namespace Cirno.Scripts.Misc;

public partial class LimitedAudioPlayer : AudioStreamPlayer2D
{
    [Export] public StringName AudioName { get; private set; }
    [Export] public bool ReparentOnCreation { get; private set; } = false;
    [Export] public float Duration { get; private set; } = -1;
    
    private bool _finished = false;

    private double _timer = 0;
    
    public override void _Ready()
    {
        if (ReparentOnCreation)
        {
            CallDeferred(MethodName.ReparentDeferred);
        }

        if (Duration >= 0)
        {
            
        }
        
        // Check if it can play
        if (IsAutoplayEnabled())
        {
            TryPlay();
        }
        
        this.Finished += OnFinished;
    }

    public override void _Process(double delta)
    {
        if (Duration >= 0 && IsPlaying())
        {
            _timer += delta;

            if (_timer >= Duration)
            {
                this.Stop();
            }
        }
    }
    
    private void ReparentDeferred()
    {
        this.Reparent(GameManager.Instance.BulletsContainer);
    }

    public override void _ExitTree()
    {
        this.Finished -= OnFinished;

        if (!_finished)
        {
            AudioManager.Instance.Stop(AudioName);
        }
    }

    public void TryPlay()
    {
        if (!AudioManager.Instance.Play(AudioName))
        {
            this.SetVolumeDb(-100);
            return;
        }
        else
        {
            this.SetVolumeDb(0);
        }
    }

    private void OnFinished()
    {
        AudioManager.Instance.Stop(AudioName);
        _finished = true;
    }
}