using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;

[RequireComponent (typeof(NavMeshAgent))]
public class CrocodileController : MonoBehaviour {
	GameObject currentTarget;
	NavMeshAgent navAgent;
	Animator animator;
	AudioSource audioSource;

	public List<AudioClip> randomSounds;
	public AudioClip snoreSound;

	bool isReading = false;
	bool startedReading = false;

	void Start()
	{
		navAgent = GetComponent<NavMeshAgent>();
		animator = GetComponent<Animator>();
		audioSource = GetComponent<AudioSource>();

		InvokeRepeating("PlayRandomSound", 0, 3);
	}

	void Update()
	{
		if (!isReading && currentTarget != null) {
			navAgent.destination = currentTarget.transform.position;
		}

		if (!startedReading && isReading && navAgent.remainingDistance == 0) {
			animator.SetTrigger("Read");

			CancelInvoke("PlayRandomSound");
			audioSource.clip = snoreSound;
			audioSource.loop = true;
			audioSource.Play();
		}
	}

	void OnTriggerEnter(Collider other) {
		if (isReading)
			return;

		if (other.name == "Hero") {
			currentTarget = other.gameObject;
			animator.SetBool("Walking", true);
		}

		if (other.name == "BookOpen") {
			currentTarget = null;

			navAgent.destination = other.transform.position;
			isReading = true;
		}
	}

	void OnTriggerExit(Collider other) {
		if (other.name == "Hero") {
			currentTarget = null;
			animator.SetBool("Walking", false);

			navAgent.destination = transform.position;
		}
	}

	void PlayRandomSound() {
		audioSource.clip = randomSounds[Random.Range(0, randomSounds.Count)];
		audioSource.Play();
	}
}
