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

public class SoundManager : MonoBehaviour {

	public static SoundManager current;

	public AudioMixerGroup audioMixerGroup;

	public AudioMixerSnapshot audioNormal;
	public AudioMixerSnapshot audioMuted;
	bool isMuted = false;

	[System.Serializable]
	public class Sound {
		public string name;
		public AudioClip[] clips;
		public int numChannels = 4;

		[System.NonSerialized]
		public List<AudioSource> channels;
	}
	public Sound[] sounds;

	public void ToggleSound() {
		if(isMuted)
			audioNormal.TransitionTo(0.1f);
		else
			audioMuted.TransitionTo(0.1f);

		isMuted = !isMuted;
	}

	void Start() {
		current = this;

		audioMixerGroup = GetComponent<AudioSource>().outputAudioMixerGroup;

		foreach(Sound s in sounds) {
			GameObject audioChannel = new GameObject();
			audioChannel.name = "Audio Channel: " + s.name;
			s.channels = new List<AudioSource>();

			for (int i = 0; i < s.numChannels; i++) {
				AudioSource src = audioChannel.AddComponent<AudioSource>();
				src.outputAudioMixerGroup = audioMixerGroup;
				s.channels.Add( src );
				src.clip = s.clips[0];
				src.playOnAwake = false;
				src.loop = false;
			}

			audioChannel.transform.SetParent(transform);
		}
	}

	public void PlaySound(string name) {
		foreach(Sound s in sounds) {
			if(s.name == name) {
				foreach(AudioSource chan in s.channels) {
					if(chan.isPlaying == false) {
						chan.clip = s.clips[ Random.Range(0, s.clips.Length) ];
						chan.Play();
						return;
					}
				}


			}
		}
	}

}
