using UnityEngine;

public class MusicManager : MonoBehaviour {

    public AudioClip chaseMusic;
    public AudioClip patrolMusic;
    public GameObject alertPrefab;
    private AudioSource audioSource;

    void Start () {
        PubSubService<AIStateChanged>.GetInstance().Suscribe(HandleAIStateChanged);
        this.audioSource = this.GetComponent<AudioSource>();
        if (this.audioSource == null || patrolMusic == null || chaseMusic == null)
            throw new System.Exception("Fix dependencies (audiosources and audioclips)");
        this.audioSource.clip = patrolMusic;
        this.audioSource.loop = true;
	}
	
    void HandleAIStateChanged(AIStateChanged _state)
    {
        switch (_state.state)
        {
            case AIAction.chase:
                this.audioSource.clip = chaseMusic;
                break;
            case AIAction.patrol:
                this.audioSource.clip = patrolMusic;
                break;
            case AIAction.caught:
                this.audioSource.clip = null;
                Instantiate(alertPrefab);
                break;
        }
        this.audioSource.Play();
    }

    private void OnDestroy()
    {
        PubSubService<AIStateChanged>.GetInstance().Unsuscribe(HandleAIStateChanged);
    }
}
