using UnityEngine;
using System.Collections.Generic;

// Idea from https://discussions.unity.com/t/play-audio-in-queue/239402/2
public class MusicManager : MonoBehaviour
{
    public AudioClip intro;

    public AudioClip loop;

    public AudioClip  outro;

    public AudioClip victory;

    private AudioSource audioSource;

    private Queue<AudioClip> clipsQueue;

    private bool isPaused = false;

    private bool needsReset = false;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        clipsQueue = new Queue<AudioClip>();

        // Intro is only played once, so we enqueue it first.
        clipsQueue.Enqueue(intro);
        ResetQueue();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
	    if (audioSource.isPlaying == false && !isPaused)
        {
	        audioSource.clip = clipsQueue.Dequeue();
            audioSource.Play();

            if(clipsQueue.Count == 0)
            {
                ResetQueue();
            }
        }
    }

    private void ResetQueue()
    {
        clipsQueue.Enqueue(loop);
        clipsQueue.Enqueue(loop);
        clipsQueue.Enqueue(loop);
        clipsQueue.Enqueue(loop);
        clipsQueue.Enqueue(outro);
    }

    public void PauseMusic()
    {
        audioSource.Pause();
        isPaused = true;
    }

    public void ResumeMusic()
    {
        if (needsReset)
        {
            clipsQueue.Clear();
            ResetQueue();
            needsReset = false;
        }

        audioSource.UnPause();
        isPaused = false;
    }

    public void PlayVictoryMusic()
    {
        audioSource.Stop();
        audioSource.PlayOneShot(victory);
        needsReset = true;
    }
}
