using System.Collections;
using UnityEngine;

namespace Audio
{
	public class MusicPlayer : MonoBehaviour
	{
		private const float CrossfadeDuration = 2f;
		
		private AudioClip currentMusic;
		
		[SerializeField] private MusicManager musicManager;
		[SerializeField] private AudioSource oldSource;
		[SerializeField] private AudioSource currentSource;

		void Awake()
		{
			musicManager.RegisterMusicPlayer(this);
		}
		
		public void PlayMusic(AudioClip music)
		{
			if (music == currentMusic)
				return;
			
			StopAllCoroutines();
			StartCoroutine(CrossFade(music));
		}

		private IEnumerator CrossFade(AudioClip music)
		{
			currentMusic = music;
			
			var newOldSource = currentSource;
			currentSource = oldSource;
			oldSource = newOldSource;
			
			currentSource.clip = music;
			currentSource.volume = 0;
			currentSource.Play();

			var oldVolumeStart = oldSource.volume;
			
			float progress = 0;
			while (progress < CrossfadeDuration)
			{
				progress += Time.deltaTime;
				progress = Mathf.Min(progress, CrossfadeDuration);
				currentSource.volume = Mathf.Lerp(0, 1f, progress / CrossfadeDuration);
				oldSource.volume = Mathf.Lerp(oldVolumeStart, 0, progress / CrossfadeDuration);
				
				yield return null;
			}
			oldSource.Stop();
			oldSource.clip = null;
		}
	}
}