﻿using UnityEngine;
using System.Collections;

public class NPC : MonoBehaviour {

	public GameObject target;

	NavMeshAgent agent;
	Vector3 origin;

	// Use this for initialization
	void Start () {
		agent = GetComponent<NavMeshAgent> ();
		//agent.SetDestination (target.transform.position);
		origin = transform.position;
	}
	
	// Update is called once per frame
	void Update () {
//		if (agent.remainingDistance < 0.1f) {
//			agent.SetDestination (origin);
//		}

//		if (Vector3.Distance (transform.position, target.transform.position) < 10f) {
//			Vector3 dir = target.transform.position - transform.position;
//			agent.SetDestination (transform.position - dir.normalized);
//		}

		RaycastHit hit;
		Vector3 forward = transform.TransformDirection (Vector3.forward * 10f);

		// add two more vectors, one to the left and one to the right
		// left adds transform.right, +1 on x axis, right subtracts the same
		// divide both by two to get 45 degrees from forward
		Vector3 left = (transform.forward + transform.right/2) * 10f;
		Vector3 right = (transform.forward - transform.right / 2) * 10f;

		// add vectors to an array
		Vector3[] rays = {forward, left, right};

		// loop through the rays
		for (int i = 0; i < rays.Length; i++) {
			
			Debug.DrawRay (transform.position, rays[i], Color.green);

			if (Physics.Raycast (transform.position, rays[i], out hit)) {
				if (hit.collider.gameObject.tag == "Player") {
					agent.SetDestination (hit.collider.gameObject.transform.position);
				}
			}
		}

		if (!agent.hasPath) {
			transform.rotation = Quaternion.Euler (0, 45f * Mathf.Sin (Time.time * 2f), 0);
		}

	}
}
