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

public class SoundController : MonoBehaviour 
{
    public static SoundController Instance;

    public AudioClip _music;

    public AudioClip _characterWalk;
    public AudioClip _explosion;
    public AudioClip _fail;
    public AudioClip _succes;

    private List<AudioSource> _sources = new List<AudioSource>();
    


    void Awake()
    {
        Instance = this;

        var source = gameObject.AddComponent<AudioSource>();
        source.clip = _music;
        source.loop = true;
        source.volume = 0.5f;
        source.Play();

        for (int i = 0; i < 15; i++)
            _sources.Add(gameObject.AddComponent<AudioSource>());
    }


    public void PlaySound(AudioClip clip, float volume = 1, bool threeDimnisional = false)
    {
        var source = FindSource();
        source.clip = clip;

        source.volume = volume;
        source.spatialBlend = threeDimnisional ? 1 : 0;

        source.Play();
    }


    private AudioSource FindSource()
    {
        for (int i = 0; i < _sources.Count; i++)
        {
            if (_sources[i].isPlaying == false)
                return _sources[i];
        }

        _sources.Add(gameObject.AddComponent<AudioSource>());
        return _sources[_sources.Count - 1];

    }

}
