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

public class AudioManager : MonoBehaviour {

    private static AudioManager _instance;

    public static AudioManager instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<AudioManager>();
            }
            return _instance;
        }
    }
        
    public AudioSource MusicSource;
    public AudioSource[] SFXSource;
    public int SFXSourceIndex;

    public AudioClip SFXPunk;
    public AudioClip SFXHendrix;
    public AudioClip SFXWoman;
    public AudioClip SFXHipster;
    public AudioClip SFXMistake;
    public AudioClip[] SFXBoo;

    int count;
    bool musicBegan = false;
    public void PlayMusic(AudioClip music)
    {
        MusicSource.loop = false;
        if (MusicSource.clip != music)
        {
            MusicSource.clip = music;
            musicBegan = true;
            //MusicSource.Play();
        }
    }

    private void Update()
    {
        if (musicBegan)
        {
            CheckIfEndGame();
        }
    }

    public void PlaySFX(AudioClip fx)
    {
        SFXSource[SFXSourceIndex].clip = fx;
        SFXSource[SFXSourceIndex].Play();
        SFXSourceIndex = (SFXSourceIndex + 1) % SFXSource.Length;
    }
    public void PlaySFX(string tName)
    {
        switch (tName)
        {
            case "Band (1)":
                SFXSource[SFXSourceIndex].clip = SFXPunk;
                break;
            case "Band (2)":
                SFXSource[SFXSourceIndex].clip = SFXHendrix;
                break;
            case "Band (3)":
                SFXSource[SFXSourceIndex].clip = SFXWoman;
                SFXSource[SFXSourceIndex].volume = 0.6f;
                break;
            case "Band (4)":
                SFXSource[SFXSourceIndex].clip = SFXHipster;
                SFXSource[SFXSourceIndex].volume = 0.7f;
                break;
            case "erro":
                SFXSource[SFXSourceIndex].clip = SFXMistake;
                SFXSource[SFXSourceIndex].volume = 0.7f;
                break;
            case "boo":
                SFXSource[SFXSourceIndex].clip = SFXBoo[Random.Range(0,2)];
                break;
            default:
                print("objeto não encontrado!");
                break;
        }
        SFXSource[SFXSourceIndex].Play();
        SFXSource[SFXSourceIndex].volume = 0.5f;
        SFXSourceIndex = (SFXSourceIndex + 1) % SFXSource.Length;
    }

    void CheckIfEndGame()
    {
        if (!MusicSource.isPlaying)
        {
            if (count == 3)
            {
                print("end");
                SceneManager.LoadScene(0);
            }
            MusicSource.Play();
            count++;
        }
    }
}
