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

public class AudioCueSource : MonoBehaviour 
{
	public AudioCue m_playOnSpawn = null;	
	public bool m_stopOnDestroy = false;
	public List<AudioCue> m_cues = new List<AudioCue>();	

	List<AudioSource> m_currSounds = new List<AudioSource>();
	
	
	public void AnimSound( Object cueName )
	{
		GameObject obj = cueName as GameObject;
		if (obj )
		{
			AudioCue cue = 	obj.GetComponent<AudioCue>();
			if ( cue != null )
			{
				if ( gameObject.layer == (int)eLayers.eGUI )
					SystemAudio.Play(cue, ref m_currSounds);				
				else 
					SystemAudio.Play(cue, transform, ref m_currSounds);				
			}
		}
	}
	
	
	public void AnimSound( string cueName )
	{
		foreach ( AudioCue cue in m_cues ) 
		{
			if ( cue != null )
			{
				if ( cueName == cue.gameObject.name )
				{
					if ( gameObject.layer == (int)eLayers.eGUI )
						SystemAudio.Play(cue, ref m_currSounds);				
					else 
						SystemAudio.Play(cue, transform, ref m_currSounds);		
					break;
				}
			}
		}
	}
	
	public void AnimSound( int cueIndex )
	{
		if ( cueIndex >= 0 && cueIndex < m_cues.Count )
		{
			AudioCue cue = m_cues[cueIndex];
			if ( cue != null )
			{
				if ( gameObject.layer == (int)eLayers.eGUI )
					SystemAudio.Play(cue, ref m_currSounds);				
				else 
					SystemAudio.Play(cue, transform, ref m_currSounds);	
			}	
				
		}
	}

	public void AnimSoundStop()
	{
		StopSounds();
	}

	void Start() { OnSpawn(); }

	// Use this for initialization
	void OnSpawn () 
	{
		if ( m_playOnSpawn )
		{			
			if ( gameObject.layer == (int)eLayers.eGUI )
				SystemAudio.Play(m_playOnSpawn, ref m_currSounds);				
			else 
				SystemAudio.Play(m_playOnSpawn, transform, ref m_currSounds);		
		}
		StartCoroutine(CoroutineClearFinishedSounds());
	}	

	void OnDestroy()
	{
		if ( m_stopOnDestroy )
			StopSounds();
	}
	void OnDisable()
	{	
		if ( m_stopOnDestroy )
			StopSounds();
	}

	void StopSounds()
	{

		for ( int i = 0; i < m_currSounds.Count; ++i )
		{
			if ( SystemAudio.HasInstance() )
				SystemAudio.Stop(m_currSounds[i], 0.2f);
			else 
			{
				AudioSource source = m_currSounds[i];
				if ( source != null && source.isPlaying )
					source.Stop();
			}
		}
		m_currSounds.Clear();
	}

	IEnumerator CoroutineClearFinishedSounds()
	{
		while( true )
		{
			yield return new WaitForSeconds(0.2f);
			for ( int i = m_currSounds.Count-1; i >= 0; --i )
			{
				AudioSource source = m_currSounds[i];
				if ( source == null || source.isPlaying == false )
					m_currSounds.RemoveAt(i);
			}
		}
	}

	/*
	// Update is called once per frame
	void Update () 
	{
	
	}
	*/
}
