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


/// <summary>
/// Class for dealing with the background music and queuing looping tracks so they hopefully play smoothly
/// </summary>
[RequireComponent(typeof(AudioSource))]
public class BackgroundMusicManager : MonoBehaviour
{
    // List of Audio clips for the background music
    public List<AudioClip> musicLibrary = new List<AudioClip>();

    private AudioSource _audioSource;
    private AudioClip _currentAudioClip;    
    private bool _pauseAudio = true;


    // Start is called before the first frame update
    void Awake()
    {
        // Get the current audio source on this GO
        _audioSource = gameObject.GetComponent<AudioSource>();              
    }

    /// <summary>
    /// Line up the next audio clip to play from the music library list, this should play after the current music track ends
    /// </summary>
    /// <param name="initialSong">Index of the Audio track in the music library</param>
    /// <param name="playOnStart">Play the audio on load or not</param>
    public void StartAudioQueue(int initialSong, bool playOnStart = true)
    {
        QueueNextAudio(initialSong);
        _pauseAudio = !playOnStart;
        PlayCurrentAudio();
    }

    public void StartAudioQueueAndPlay(int initialSong)
    {
        StartAudioQueue(initialSong, true);
    }

    // Set/Change the next audio to play
    public void QueueNextAudio(int songIndex)
    {        
        if (musicLibrary[songIndex] != null)
        {
            _currentAudioClip = musicLibrary[songIndex];
        }
        
    }

    // Stop the audio but keep scanning for changes
    public void StopAudioNow()
    {
        _audioSource.Stop();
        _pauseAudio = true;
        CancelInvoke("PlayCurrentAudio");
        Invoke("PlayCurrentAudio", 0.1f);
    }

    // Stop the audio and instantly play the next track
    public void StopCurrentAudioAndPlay(int songIndex)
    {
        _audioSource.Stop();
        CancelInvoke("PlayCurrentAudio");
        StartAudioQueueAndPlay(songIndex);
    }

    // Stop the audio and the cancel the invoke
    public void StopCurrentAudioForGood()
    {
        _audioSource.Stop();
        CancelInvoke("PlayCurrentAudio");
    }

    public void PlayCurrentAudio()
    {
        if (!_pauseAudio)
        {
            _audioSource.clip = _currentAudioClip;
            _audioSource.Play();
            Invoke("PlayCurrentAudio", _audioSource.clip.length);
        }
        else
        {
            _audioSource.Stop();
            Invoke("PlayCurrentAudio", 0.1f);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
