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>();

    [SerializeField]
    private List<int> _loopQueue = new List<int>();

    private AudioSource _audioSource;
    private AudioClip _currentAudioClip;    
    public static bool pauseAudio = true;
    public static bool stopAudio = false;
    private TimerHelper _audioTimer;
    private bool _forceChange;
    private int _currentLoopIndex;


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

    /// <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;
        _forceChange = true;
        PlayCurrentAudio();
    }

    public void CreateLoopQueue(params int[] trackIDs)
    {
        _loopQueue.Clear();
        _loopQueue.AddRange(trackIDs);
        _currentLoopIndex = 0;
    }

    public void QueueIntroThenLoopQueue(int initialSong, params int[] trackIDs)
    {
        _currentAudioClip = musicLibrary[initialSong];
        CreateLoopQueue(trackIDs);
        _currentLoopIndex = -1;
    }

    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()
    {        
        pauseAudio = true;
    }

    // Stop the audio and instantly play the next track
    public void StopCurrentAudioAndPlay(int songIndex)
    {        
        _forceChange = true;
        StartAudioQueueAndPlay(songIndex);
    }

    // Stop the audio and the cancel the invoke
    public void StopCurrentAudioForGood()
    {
        stopAudio = true;
    }

    public void PlayCurrentAudio()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (!stopAudio)
        {
            if (!pauseAudio)
            {
                if (_forceChange || _audioTimer.HasTicked(Time.unscaledDeltaTime))
                {
                    if (_loopQueue.Count > 0 )
                    {
                        // Let a song play before the loop starts
                        if (_currentLoopIndex == -1)
                        {
                            _currentLoopIndex = 0;
                        }
                        else
                        {
                            _currentAudioClip = musicLibrary[_loopQueue[_currentLoopIndex]];
                            if (_currentLoopIndex >= _loopQueue.Count - 1)
                            {
                                _currentLoopIndex = 0;
                            }
                            else
                            {
                                _currentLoopIndex++;
                            }
                        }
                    }
                    _audioSource.clip = _currentAudioClip;
                    _audioSource.Play();
                    _audioTimer = new TimerHelper(_audioSource.clip.length, false);
                    _forceChange = false;
                }
            }
            else
            {
                _audioSource.Pause();
            }
        }
        else
        {
            _audioSource.Stop();
        }
    }
}
