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

public class PatrolBehavior : MonoBehaviour {
	[SerializeField]
	List<GameObject> path;
	[SerializeField]
	private float speed = 2.0f;
	[SerializeField]
	private float acceleration = 3.0f;
	[SerializeField]
	float pathTriggerDistance = 2.0f;

	int target;
	int m_startTarget = 0;

	public bool isActive {get; set;}
	[SerializeField]
	bool m_startActive = true;



	Rigidbody myRigidbody;

	[SerializeField]
	GameObject hero;
	// Use this for initialization
	
	void Start () {
		isActive = m_startActive;
		target = m_startTarget;
        myRigidbody = rigidbody;

        if (hero == null)
        {
            hero = FindObjectOfType<Hero>() ? FindObjectOfType<Hero>().gameObject : null;
        }
	}
	 
	// Update is called once per frame
	void Update () {
		if (isActive) { 
			move();
		}
	}
	
	void move() {
		if (path.Count <= target || path.Count == 0)
		{
			return;
		}
		transform.LookAt(path[target].transform, new Vector3(0.0f, 0.0f, -1.0f));
		Vector3 toTarget = path[target].transform.position - transform.position;
		float distanceToTarget = toTarget.magnitude;
		
		if (distanceToTarget <= pathTriggerDistance)
		{
		target++;
			if (path.Count <= target)
				target = 0;
			return;
		}
		if (myRigidbody != null)
		{
			Vector3 desiredVelocity = speed * toTarget / distanceToTarget;
			Vector3 desiredImpulse = desiredVelocity - myRigidbody.velocity;
			Vector3 realImpulse = Vector3.ClampMagnitude(desiredImpulse, acceleration * Time.deltaTime);
			myRigidbody.AddForce(realImpulse, ForceMode.VelocityChange);
		}
		else
			transform.position = Vector3.MoveTowards(transform.position, path[target].transform.position, speed * Time.deltaTime);
	}

	public void activate()
	{
		isActive = true;
	}

	public void deactivate()
	{
		isActive = false;
	}
}