using UnityEngine;
using System.Collections;

public class ChaseFly : MonoBehaviour {

	public GameObject target;

	private enum ActionEnum {MOVE, IDLE, SWAT}; 
	private ActionEnum current_action, previous_action;
	private Vector3 velocity = Vector3.zero;
	private float swattime = 0.6f;

	// Use this for initialization
	void Start () {
		current_action = ActionEnum.IDLE;
		animation.Play("idle");
	}

	void DecideNextAction() {
		// are you close enough?
		if(current_action == ActionEnum.SWAT) {
			if(swattime < 0) {
				current_action = ActionEnum.IDLE;
			} else {
				swattime -= Time.deltaTime;
		//		Debug.Log (swattime);
			}
		}
		if(current_action == ActionEnum.MOVE) velocity = transform.forward * 0.5f;

		if(Vector3.Distance(target.transform.position, transform.position) < 5 && current_action == ActionEnum.IDLE) {
			current_action = ActionEnum.MOVE;
		}
		if(Vector3.Distance(target.transform.position, transform.position) < 1.5f && current_action == ActionEnum.MOVE) {
			current_action = ActionEnum.SWAT;
			velocity = Vector3.zero;
			swattime = 0.6f;
		}
		if(Vector3.Distance(target.transform.position, transform.position) > 6 && current_action == ActionEnum.MOVE)
		{
			current_action = ActionEnum.IDLE;
			velocity = Vector3.zero;
		}
	}

	// Update is called once per frame
	void Update () {
		Vector3 updatepos = new Vector3(target.transform.localPosition.x, transform.position.y, target.transform.localPosition.z); 
		transform.LookAt(updatepos);
		if(current_action != previous_action) {
			switch(current_action) {
			case(ActionEnum.IDLE): animation.Play("idle");
				break;
			case(ActionEnum.MOVE): animation.Play("walk");
				break;
			case(ActionEnum.SWAT): animation.Play("swat");
				break;
			}
			previous_action = current_action;
		}
		DecideNextAction();
		transform.position += velocity * Time.deltaTime;
	}
}
