using System.Collections.Generic;
using Godot;

namespace Cirno.Scripts.Misc;

public partial class AudioManager : Node2D
{
    public static AudioManager Instance { get; private set; }

    [Export]
    public int ConcurrentSounds { get; set; } = 3;
    
    private Dictionary<string, int> _audioDict = new Dictionary<string, int>();

    public override void _Ready()
    {
        Instance = this;
    }

    public bool CanPlay(string audioName)
    {
        var item = _audioDict.TryGetValue(audioName, out int amount);
        if (item) return amount < ConcurrentSounds;
        _audioDict.Add(audioName, 0);
        return true;
    }

    public bool Play(string audioName)
    {
        if (!CanPlay(audioName)) return false;
        if (!_audioDict.ContainsKey(audioName))
        {
            _audioDict.Add(audioName, 0);
        }
        _audioDict[audioName] += 1;

        return true;
    }

    public void Stop(string audioName)
    {
        if (_audioDict.ContainsKey(audioName))
        {
            _audioDict[audioName] -= 1;

            if (_audioDict[audioName] < 0)
            {
                _audioDict[audioName] = 0;
            }  
        }
    }
}