using UnityEngine;
using System.Collections;

public class MusicManager : MonoBehaviour
{
    public static MusicManager Instance;

    private AudioSource musicSource;

    [Header("Music Volume")]
    public float normalVolume = 0.3f;
    public float duckedVolume = 0.08f;

    private Coroutine duckCoroutine;

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

            musicSource = GetComponent<AudioSource>();

            if (musicSource != null)
            {
                musicSource.volume = normalVolume;
            }
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void DuckMusic(float duration)
    {
        if (musicSource == null) return;

        if (duckCoroutine != null)
        {
            StopCoroutine(duckCoroutine);
        }

        duckCoroutine = StartCoroutine(DuckMusicRoutine(duration));
    }

    private IEnumerator DuckMusicRoutine(float duration)
    {
        musicSource.volume = duckedVolume;

        yield return new WaitForSeconds(duration);

        musicSource.volume = normalVolume;
    }
}