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

public class SfxController : MonoBehaviour
{
    public Dictionary<string, AudioSource> innerDict;

	public static SfxController instance;

    // Options
    public bool useGameObjectNames = false;

    void Awake()
	{
		instance = this;

        innerDict = new Dictionary<string, AudioSource>();
        AudioSource[] sources = gameObject.GetComponentsInChildren<AudioSource>();
        foreach (var s in sources)
            if (useGameObjectNames)
                innerDict[s.gameObject.name] = s;
            else
                innerDict[s.clip.name] = s;
    }

	//void Update(){
	//	if (Input.anyKeyDown)
	//		Application.LoadLevel ("GameOver");
	//}

    public void PlaySound(string name, float pitchVariance = 0)
    {
        if (innerDict.ContainsKey(name))
        {
            //if a new audio file is going to be played then we stop all the other before
            foreach (KeyValuePair<string, AudioSource> audiosrc in innerDict) {

                if (audiosrc.Key.Contains("dance_") && audiosrc.Value.isPlaying)
                {
                    audiosrc.Value.Stop();
                }
            }
           


            if (pitchVariance != 0) innerDict[name].pitch = 1 + Random.Range(-pitchVariance, pitchVariance);
            innerDict[name].Play();
        }
        else Debug.LogWarning("No sound of name " + name + " exists");
    }

    public void PlaySoundClick()
    {
        innerDict["effect_click"].Play();
    }

    public void PlaySoundOver() {
        innerDict["effect_over"].Play();
    }

    public void MuteAll()
    {
        foreach (AudioSource s in innerDict.Values) s.mute = true;
    }
    public void UnmuteAll()
    {
        foreach (AudioSource s in innerDict.Values) s.mute = false;
    }
}