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

public class SoundController : MonoBehaviour {
    public Dictionary<string, AudioClip> sounds = new Dictionary<string, AudioClip>();
    public GameObject theCamera;
    List<AudioClip> soundList = new List<AudioClip>();
    List<AudioSource> audioSources = new List<AudioSource>();
    void Start() {
        soundList = (Resources.LoadAll<AudioClip>("Sounds/")).ToList();

        foreach (AudioClip sound in soundList) {
            sounds.Add(sound.name, sound);
        }
    }

    public void PlaySound(string name) {
        AudioSource audioSource = theCamera.AddComponent<AudioSource>();
        audioSource.clip = sounds[name];
        audioSource.volume = 0.5f;
        audioSource.Play();
        audioSources.Add(audioSource);
    }

    public void ToggleSoundPlayOnLoop(string name) {
        AudioSource audioSource = theCamera.AddComponent<AudioSource>();
        AudioClip sound = sounds[name];
        audioSource.volume = 0.5f;
        audioSource.loop = !audioSource.loop;
        audioSource.clip = sounds[name];
        audioSource.Play();
        audioSources.Add(audioSource);
    }

    void Update() {
            if (audioSources.Count > 0 && audioSources != null) {
                foreach (AudioSource audioSource in audioSources) {
                    if (!audioSource.isPlaying) {
                        Destroy(audioSource);
                    }
            }
        }
    }
}
