using System.Collections;
using UnityEngine;

namespace Managers
{
    public class BGM : MonoBehaviour
    {
        [SerializeField] AudioSource bgmPlayer;
        private AudioClip _currentMusic;

        public void SetCurrentMusic(AudioClip music, float fadeTime = 0)
        {
            if (fadeTime > 0)
            {
                StartCoroutine(FadeSong(fadeTime, music));
            }
            else
            {
                bgmPlayer.Stop();
                bgmPlayer.clip = music;
                bgmPlayer.Play();
            }
        }

        private IEnumerator FadeSong(float fadeTime, AudioClip music)
        {
            var timePassed = 0f;
            var startVolume = bgmPlayer.volume;
            
            if (bgmPlayer.clip)
            {
                while (timePassed < fadeTime / 2f)
                {
                    timePassed += Time.deltaTime;
                    bgmPlayer.volume = Mathf.Lerp(startVolume, 0f, timePassed / (fadeTime / 2f));
                    yield return null;
                }

            }

            bgmPlayer.volume = 0f;
            if (!music) yield break;
            bgmPlayer.clip = music;
            bgmPlayer.Play();
            timePassed = 0f;
            while (timePassed < fadeTime / 2)
            {
                timePassed += Time.deltaTime;
                bgmPlayer.volume = Mathf.Lerp(0f, startVolume, timePassed / (fadeTime / 2f));
                yield return null;
            }
            
            bgmPlayer.volume = startVolume;
        }
    }
}
