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

[System.Serializable]
public struct MusicMapping
{
    public string sceneName;
    public AudioClip track;
}
public class MusicManager : MonoBehaviour
{
    public bool musicEnabled = true;
    public MusicMapping[] musicMap;
    public float crossfadeSpeed = 1;
    public AudioSource[] audioSources;
    public int activeAudioSource = 0;
    [Range(0,1)]
    public float crossfadeT = 1;

    private void Awake()
    {
        if (GameObject.FindObjectsOfType<MusicManager>().Length != 1)
        {
            Destroy(this);
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        DontDestroyOnLoad(this);
        SceneManager.sceneLoaded += this.OnSceneLoaded;

        this.LoadMeppedTrack(SceneManager.GetActiveScene().name);
    }

    private void Update()
    {
        this.crossfadeT = Mathf.Clamp( this.crossfadeT += this.activeAudioSource == 0 ?  .1f * this.crossfadeSpeed : -.1f * this.crossfadeSpeed, 0, 1);
        float val = Mathf.Lerp(0, 1, this.crossfadeT);
        this.audioSources[0].volume = val;
        this.audioSources[1].volume = 1 - val;

        if (this.musicEnabled == false)
        {
            this.audioSources[0].volume = 0;
            this.audioSources[1].volume = 0;
        }

    }

    private void LoadMeppedTrack(string sceneName)
    {
        foreach (MusicMapping mapping in this.musicMap)
        {
            if (mapping.sceneName == sceneName)
            {
                this.CrossfadeToTrack(mapping.track);
                Debug.Log("MusicManager: Fading to track " + mapping.track.name);
            }
        }
    }

    public bool ToggleMusic()
    {
        this.musicEnabled = !this.musicEnabled;

        return this.musicEnabled;
    }
    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        this.LoadMeppedTrack(scene.name);   
    }

    public void CrossfadeToTrack(AudioClip audioClip, float speed)
    {
        this.crossfadeSpeed = speed;
        if (this.audioSources[this.activeAudioSource].clip == audioClip) { return; } //Don't fade if it's the same clip
        if (this.activeAudioSource == 0)
        {
            this.audioSources[1].clip = audioClip;
            this.audioSources[1].Play();
            this.activeAudioSource = 1;
        }
        else
        {
            this.audioSources[0].clip = audioClip;
            this.audioSources[0].Play();
            this.activeAudioSource = 0;
        }
    }
    public void CrossfadeToTrack(AudioClip audioClip)
    {
        this.CrossfadeToTrack(audioClip, 1f);
    }
}
