﻿using UnityEngine;
using System.Collections;

public class MusicPlayer : MonoBehaviour
{
    public static MusicPlayer instance = null;

    public AudioClip TitleScreenClip;
    public AudioClip[] LevelsClips;

    private AudioSource mAudioSource;

    void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            print("Duplicate music player self-destructing!");
        }
        else
        {
            instance = this;
            GameObject.DontDestroyOnLoad(gameObject);
            mAudioSource = GetComponent<AudioSource>();
            PlayTitleScreenMusic();
        }
    }

    public void PlayTitleScreenMusic()
    {
        if (mAudioSource.clip == TitleScreenClip) return;
        mAudioSource.clip = TitleScreenClip;
        mAudioSource.Play();
        mAudioSource.loop = true;
    }
    

    public void PlayLevelMusic( int level)
    {
        mAudioSource.clip = LevelsClips[level-1];
        mAudioSource.Play();
        mAudioSource.volume = 0.2f;
    }

    public void Pause()
    {
        mAudioSource.Pause();
    }
    public void UnPause()
    {
        mAudioSource.UnPause();
    }

    public IEnumerator _VolumeTransition(float speed, bool increase)
    {
        WaitForEndOfFrame wait = new WaitForEndOfFrame();
        while (true)
        {
            float vol = mAudioSource.volume;
            if (increase)
            {
                mAudioSource.volume = Mathf.Lerp(vol, 1f, Time.deltaTime * speed);
                if (vol >= 0.9)
                {
                    mAudioSource.volume = 1f;
                    break;
                }
            }
            else
            {
                mAudioSource.volume = Mathf.Lerp(vol, 0f, Time.deltaTime * speed);
                if (vol <= 0.1)
                {
                    mAudioSource.volume = 0f;
                    break;
                }
            }

            yield return wait;
        }
    }

}
