using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;

namespace OCES.Audio
{
    public class AudioSourcePool
    {
        readonly Transform m_root;
        readonly Queue<GameObject> m_audioSourcePool = new();
        int m_counter;
        AudioMixerGroup m_mixerGroup;

        public AudioSourcePool(Transform root, AudioMixerGroup mixerGroup = null)
        {
            this.m_root = root;
            this.m_mixerGroup = mixerGroup;
        }
        
        public AudioSource AcquireAudioSource()
        {
            GameObject go;
            if (this.m_audioSourcePool.Count > 0)
            {
                go = this.m_audioSourcePool.Dequeue();
                go.SetActive(true);
            }
            else
            {
                this.m_counter++;
                go = new GameObject($"AudioSource{this.m_counter}");
                go.transform.SetParent(this.m_root, false);
                go.AddComponent<AudioSource>();
            }
            
            AudioSource audioSource = go.GetComponent<AudioSource>();
            audioSource.outputAudioMixerGroup = this.m_mixerGroup;
            return audioSource;
        }
        
        public void ReturnToPool(GameObject go)
        {
            AudioSource audioSource = go.GetComponent<AudioSource>();
            audioSource.clip = null;
            go.SetActive(false);
            this.m_audioSourcePool.Enqueue(go);
        }
    }
}
