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

public class AudioManager : MonoBehaviour
{
    public List<AudioClip> audioClips;
    public List<GameObject> audioPlayers;
    public GameObject emptyGameObject;
    private bool bgmison = false;
    private int bgmplayingindex;
    void Awake()
    {
        DontDestroyOnLoad(this);
    }
    void OnEnable() 
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }
    
    void OnDisable() 
    {
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }
    
    private void OnSceneLoaded(Scene scene, LoadSceneMode mode) 
    {
        if(bgmplayingindex == 4)
        {
            if(bgmison == true)
                bgmison = false;
        }
    }
    void Update()
    {
        if(bgmison == false && SceneManager.GetActiveScene().name != "Main Menu")
        {
            PlayAudio(1, true, false);
            bgmison = true;
            bgmplayingindex = 1;
        }
        if(bgmison == false && SceneManager.GetActiveScene().name == "Main Menu")
        {
            PlayAudio(4, true, true);
            bgmison = true;
            bgmplayingindex = 4;
        }
    }
    
    public void PlayAudio(int i, bool loop, bool DOL)
    {
        GameObject audioPlayer = Instantiate(emptyGameObject,new Vector3(0,0,0),Quaternion.identity);
        audioPlayers.Add(audioPlayer);
        audioPlayer.AddComponent<AudioSource>();
        audioPlayer.GetComponent<AudioSource>().clip = audioClips[i];
        audioPlayer.GetComponent<AudioSource>().volume = 0.5f;
        audioPlayer.GetComponent<AudioSource>().Play();
        if(loop == true)
        {
            audioPlayer.GetComponent<AudioSource>().loop = true;
        }
        audioPlayer.AddComponent<AudioController>();
        if(DOL == true)
        {
            audioPlayer.GetComponent<AudioController>().DoDestroyOnLoad();
        }
    }

    public void ButtonClick()
    {
        PlayAudio(3,false,false);
    }
}
