#pragma strict

var loopTime : float;
var fadeoutStart: float;
var fadeinStart: float;
var listMusic : AudioClip[] = new AudioClip[12];
private var listMusicShuffle : AudioClip[] = new AudioClip[12];

var tracciaestratta;
var numeroRound = 1;

var audio1Volume : float = 1.0;
var audio2Volume : float = 0.0;

var myBackgroundAudioSource : AudioSource;
var myAudioSource : AudioSource;

function Start () {
	
	myBackgroundAudioSource = gameObject.GetComponents(AudioSource)[0];
	myAudioSource = gameObject.GetComponents(AudioSource)[1];
	
}

function StartMusic() {

	loopTime = Time.time;
	RandomizeListMusic(listMusic);
	fadeoutStart = 17.0f;
	fadeinStart = 19.0f;
	
	myBackgroundAudioSource.mute = true;
	
	myAudioSource.clip = listMusicShuffle[0];	
	myAudioSource.Play();

}

function RandomizeListMusic(arr : Object[])
 {
  	 //Debug.Log("Lunghezza Lista "+arr.Length);
     for (var i = arr.Length - 1; i > 0; i--) {
         var r = Random.Range(0, i + 1);
         var tmp = arr[i];
         arr[i] = arr[r];
         arr[r] = tmp;
     }
     
     listMusicShuffle = arr;
     //Debug.Log("Lunghezza Lista SHUFFLED  "+listMusicShuffle.Length);
 }
 
function estraiMusica()
{
	tracciaestratta = RandomMusic();
	myAudioSource.clip = listMusicShuffle[tracciaestratta];
}

function RandomMusic() : int
{
	return Random.Range(0,listMusicShuffle.Length);
}

function Update () {

	if (myAudioSource.isPlaying)
	{
		Debug.Log("TIME : "+Time.time+" LOOPTIME "+loopTime);
		if (Time.time > (loopTime + 17.0f))
		{
			loopTime = Time.time;
			Debug.Log("PASSATI 17 secondi");
		}
	}
	if (!myAudioSource.isPlaying)
	{
		Debug.Log ("NUMERO ROUND "+numeroRound);
		numeroRound++;
		myAudioSource.clip = listMusicShuffle[numeroRound];
		myAudioSource.Play();
	}
	//Debug.Log(loopTime);
	//loopTime += 1 * Time.deltaTime;
	//if (loopTime >= 10.0f)
	//{
	//	audio.Stop();
	//	loopTime = 0.0f;
	//	estraiMusica();
	//	audio.Play();
	//}
	//	fadeOut();
	//	
	//if (audio.volume == 0 && loopTime <= 13.0f)
	//	fadeIn();
	//	
	//if (loopTime == 20.0f)
	//{
	//	audio.Stop();
	//}
}
 
function fadeIn() {
     if (audio2Volume < 1) {
         audio2Volume += 0.1 * Time.deltaTime;
         myAudioSource.volume = audio2Volume;
     }
 }
 
function fadeOut() {
     if(audio1Volume > 0.1)
     {
         audio1Volume -= 0.1 * Time.deltaTime;
         myAudioSource.volume = audio1Volume;
     }
 }