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

public class MusicManager : BaseBehaviour
{

	[SerializeField]
	private AudioSource[] musicTracks;
	[SerializeField]
	private float fadeTime = 2;

	private int currentTrackIndex;

	private void Awake()
	{
		currentTrackIndex = Random.Range(0, musicTracks.Length);

		if (musicTracks.Length > 0)
		{
			musicTracks[currentTrackIndex].volume = 0;
            musicTracks[currentTrackIndex].Play();
		}
	}

	private void Update()
	{
		if (musicTracks.Length == 0) return;

		if(musicTracks[currentTrackIndex].isPlaying)
		{
			var currentTrack = musicTracks[currentTrackIndex];
			if(currentTrack.time < fadeTime)
			{
				currentTrack.volume = currentTrack.time / fadeTime;
			}
			else if(currentTrack.time > currentTrack.clip.length - fadeTime)
			{
				currentTrack.volume = 1 - (currentTrack.time - (currentTrack.clip.length - fadeTime));
			}
			else
			{
				currentTrack.volume = 1;
			}
        }
		else
		{
			musicTracks[currentTrackIndex].Stop();
			currentTrackIndex = (currentTrackIndex + 1) % musicTracks.Length;
			musicTracks[currentTrackIndex].volume = 0;
			musicTracks[currentTrackIndex].Play();
		}
	}

}
