using UnityEngine;
using System.Collections;

public class MusicManager : MonoBehaviour {

    public AudioSource m_audioSource;
    public AudioClip[] m_battleMusic;
    public AudioClip m_menuMusic;

    public static MusicManager ms_instance;
    public static MusicManager Instance
    {
        get { return ms_instance; }
    }

    public bool m_inMenus = true;
    public bool m_isPlaying = false;
    float m_timeToBuffer;

    float m_defaultVolume;
    float m_speechVolume;

	// Use this for initialization
	void Start () {

        if (ms_instance != null)
        {
            Debug.LogError("Only one musicman allowed");
        }
        ms_instance = this;
        m_audioSource.loop = false;
        m_defaultVolume = m_audioSource.volume * 0.65f;
        m_speechVolume = m_audioSource.volume * 0.45f;

        //PlayNextTrack();
	}

    void SetInMenus(bool inmen)
    {
        if ( m_inMenus != inmen )
        {
            m_inMenus = inmen;
            m_audioSource.Stop();
            PlayNextTrack();
        }
    }

    void PlayNextTrack()
    {

        if (m_inMenus)
        {
            m_audioSource.clip = m_menuMusic; 
        }
        else
        {
            m_audioSource.clip = (m_battleMusic[Random.Range(0, m_battleMusic.Length)]);
        }
        Debug.Log("New Music Track: " + m_audioSource.clip.name);
        m_audioSource.Play();

        //m_timeToBuffer = 5.0f;
    }
	
	// Update is called once per frame
	void Update ()
    {
        float destVol;
        if ( VoiceManager.Instance.IsPlaying )
        {
            destVol = m_speechVolume;
        }
        else
        {
            destVol = m_defaultVolume;
        }

        float newVol = Mathf.Lerp(m_audioSource.volume, destVol, Time.deltaTime);
        m_audioSource.volume = newVol;

        SetInMenus(MenuSystem.InBattle == false);

        //m_timeToBuffer -= Time.deltaTime;
        //if ( m_timeToBuffer < 0.0 )
        {
            if (m_audioSource.clip == null )
            {
                PlayNextTrack();
            }
            else if ( m_audioSource.clip.isReadyToPlay )
            {
                if (m_audioSource.isPlaying == false)
                {
                    PlayNextTrack();
                }
            }
        }
	}
}
