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

public class AudioManager : MonoBehaviour
{
    public static AudioManager Instance;

    public AudioSource MusicSource;
    public float FadeDuration = 0.5f;
    public AudioClip MenuMusic;
    public AudioClip FightMusic;
    public AudioClip VictoryMusic;
    public AudioClip DefeatMusic;

    private bool _fading;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
    }

    private void Start()
    {
        PlayMenuMusic();
    }

    private void Update()
    {
#if UNITY_EDITOR
        if (Input.GetKeyUp(KeyCode.S))
        {
            if (MusicSource.clip == null)
            {
                PlayMenuMusic();
            }
            else
            {
                if (MusicSource.clip == MenuMusic)
                {
                    PlayFightMusic();
                }
                else
                {
                    PlayMenuMusic();
                }
            }
        }
#endif
    }

    public void PlayMenuMusic()
    {
        if (!_fading)
        {
            StartCoroutine(FadeInMusic(MenuMusic));
        }
    }

    public void PlayFightMusic()
    {
        if (!_fading)
        {
            StartCoroutine(FadeInMusic(FightMusic));
        }
    }

    public void PlayVictoryMusic()
    {
        if (!_fading)
        {
            StartCoroutine(FadeInMusic(VictoryMusic));
        }
    }

    public void PlayDefeatMusic()
    {
        if (!_fading)
        {
            StartCoroutine(FadeInMusic(DefeatMusic));
        }
    }

    private IEnumerator FadeInMusic(AudioClip track)
    {
        _fading = true;
        float t = Time.time + FadeDuration;
        float vol = MusicSource.volume;
        float alpha = 0;

        if (MusicSource.isPlaying)
        {
            while (Time.time < t)
            {
                alpha = (t - Time.time) / FadeDuration;
                MusicSource.volume = Mathf.Lerp(0, vol, alpha);
                yield return null;
            }
            MusicSource.volume = 0;
            MusicSource.clip = track;
            MusicSource.Play();
            t = Time.time + FadeDuration;
            while (Time.time < t)
            {
                alpha = (t - Time.time) / FadeDuration;
                MusicSource.volume = Mathf.Lerp(vol, 0, alpha);
                yield return null;
            }
            MusicSource.volume = vol;
            _fading = false;
        }
        else
        {
            MusicSource.clip = track;
            MusicSource.Play();
            t = Time.time + FadeDuration;
            while (Time.time < t)
            {
                alpha = (t - Time.time) / FadeDuration;
                MusicSource.volume = Mathf.Lerp(vol, 0, alpha);
                yield return null;
            }
            MusicSource.volume = vol;
            _fading = false;
        }
    }
}
