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

public class AudioManager : MonoBehaviour {
	private string audioPath = "Audio";

	private List<AudioClip> preLoadedAudioClips = new List<AudioClip>();

	private static AudioManager instance;

	public static AudioManager Instance {
		get {
			if (instance == null) {
				instance = new GameObject("AudioManager").AddComponent<AudioManager>();
			}
			return instance;
		}
	}

	public void PreloadAudioFile (string audioName) {
		preLoadedAudioClips.Add (GetAllAudioClips (audioName));
	}

	public AudioClip Play (string audioName, float volume = 1f, bool loop = false) {
        GameObject newGO = new GameObject(audioName);
		AudioSource audioSource = newGO.AddComponent<AudioSource> ();

		audioSource.transform.parent = this.transform;

		audioSource.audio.clip = GetAllAudioClips (audioName);
	
		audioSource.volume = volume;
		audioSource.loop = true;

		audioSource.Play ();

		if (!loop) {
			StartCoroutine (DestroyAudioSource(audioSource.gameObject));
			Resources.UnloadUnusedAssets ();
		}

        return audioSource.clip;
	}

	public void Stop (string audioName) {
		GameObject tempObject = GameObject.Find (audioName);
		Destroy (tempObject);
	}

	AudioClip GetAllAudioClips (string audioName) {
		AudioClip audioClip = null;
		AudioClip[] audioClips = (AudioClip[])Resources.LoadAll<AudioClip>(audioPath);

		foreach (AudioClip clip in audioClips) {
			if (clip.name == audioName) {
				audioClip = clip;
			} 
		}

		return audioClip;
	}

	IEnumerator DestroyAudioSource (GameObject source) {
		yield return new WaitForSeconds (source.audio.clip.length);
		Destroy (source);
	}
}
