using UnityEngine;
using DG.Tweening;

public class MusicSwitcher : MonoBehaviour
{
	public AudioSource fullSong;
	public AudioSource halfSong;
	public AudioSource noSong;

	public string DEBUG;

	private float songEnergy;
	private float currentSong=1;

	void Update()
	{
		SyncSamples();

		if (EnergyTracker.totalEnergy > 45)
		{
			songEnergy = Mathf.Min(100, songEnergy + 0.33f);
		}
		else if (EnergyTracker.totalEnergy > 25)
		{
			if (songEnergy < 5)
			{
				songEnergy++;
			}
			else
			{
				songEnergy = Mathf.Max(5, songEnergy - 0.33f);
			}
		}
		else
		{
			songEnergy = Mathf.Max(-5, songEnergy - 0.1f);
		}

		if(songEnergy < 0)
		{
			if (currentSong != 1)
				PlayNoSong();
		}
		else if (songEnergy < 50)
		{
			if (currentSong != 2)
				PlayHalfSong();
		}
		else
		{
			if (currentSong != 3)
				PlayFullSong();
		}

		DEBUG = "E: " + EnergyTracker.totalEnergy + "; S: " + songEnergy;
		//CheckDebugKeys();
	}

	private void CheckDebugKeys()
	{
		if (Input.GetKey(KeyCode.Alpha1))
		{
			PlayNoSong();
		}
		else if (Input.GetKey(KeyCode.Alpha2))
		{
			PlayHalfSong();
		}
		else if (Input.GetKey(KeyCode.Alpha3))
		{
			PlayFullSong();
		}
	}

	private void SyncSamples()
	{
		halfSong.timeSamples = fullSong.timeSamples;
		noSong.timeSamples = fullSong.timeSamples;
	}

	private void PlayNoSong()
	{
		currentSong = 1;
		noSong.DOFade(0.8f, 2f);
		halfSong.DOFade(0.0f, 2f);
		fullSong.DOFade(0.0f, 2f);
	}

	private void PlayHalfSong()
	{
		currentSong = 2;
		noSong.DOFade(0.0f, 2f);
		halfSong.DOFade(0.75f, 2f);
		fullSong.DOFade(0.0f, 2f);
	}

	private void PlayFullSong()
	{
		currentSong = 3;
		noSong.DOFade(0.0f, 2f);
		halfSong.DOFade(0.0f, 2f);
		fullSong.DOFade(0.85f, 2f);
	}

	void Start()
    {
		songEnergy = -5f;
		PlayNoSong();
	}
}
