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

public class MusicManager : MonoBehaviour
{
	public enum musicType {
		easy,
		medium,
		hard
	}

	public AudioSource[] audioSources;

	public AudioSource lastOne;
	public AudioSource newOne;
	private musicType lastMusicSound;

	public float timeChangingmusic = 1f;

	public bool playingMusic = false;

	private static MusicManager instance;
	public static MusicManager Instance {
		get {
			return instance;
		}
	}

	private void Awake() {
		instance = this;
	}

	public void SetMusicType(musicType type) {
		if (type!= lastMusicSound) {
			switch (type) {
				case (musicType.easy):
					lastOne = newOne;
					newOne = audioSources[(int)musicType.easy];
					lastMusicSound = type;
					break;
				case (musicType.medium):
					lastOne = newOne;
					newOne = audioSources[(int)musicType.medium];
					lastMusicSound = type;
					break;
				case (musicType.hard):
					lastOne = newOne;
					newOne = audioSources[(int)musicType.hard];
					lastMusicSound = type;
					break;
			}
			StartCoroutine(ChangeMusic());
		}
	}

	IEnumerator ChangeMusic() {
		float value = 0f;
		bool finished = false;
		float timer = 0;
		while (!finished) {
			timer += Time.deltaTime;
			value = Mathf.Lerp(0, 1, timer / timeChangingmusic);
			newOne.volume = value;
			lastOne.volume = 1-value;
			if (timer > timeChangingmusic) {
				finished = true;
			}
			yield return null;
		}
	}

	public void StopMusic() {
		playingMusic = false;
		for (int x=0;x< audioSources.Length;++x) {
			audioSources[x].Stop();
		}
	}

	public void ResumeMusic() {
		playingMusic = true;
		for (int x = 0; x < audioSources.Length; ++x) {
			audioSources[x].Play();
		}
	}
}
