var target : Transform;
var moveSpeed : float = 3.0;
var damageAmount : int = 1;
var health : int = 1;
var beginTarget : Vector3;
var range : int = 10;
var timeAlert : float = 0.0;

private var hiding : float = 0;

gameObject.tag = "Roach";
beginTarget = transform.position;

function Update () {
	if(!(health <= 0)){
		hiding -= Time.deltaTime;
		timeAlert -= Time.deltaTime;
		if(!target){
			if(gameObject.FindWithTag("Player")){
				target = gameObject.FindWithTag("Player").transform;
			}
		}
		if(Vector3.Distance(target.position, transform.position) < range && !(hiding > 0.0))
			transform.LookAt(target);
		if((PlayerInView() || timeAlert > 0.0) && !(hiding > 0.0)){
			var temp = target.position;
			temp.y = transform.position.y;
			transform.LookAt(temp);
			animation.Play("Walk");
			transform.Translate(0, 0, moveSpeed * Time.deltaTime);
			timeAlert = 2.0;
		} else if(Vector3.Distance(transform.position, beginTarget) < 1.0){
			animation.Play("Idle");
		} else {
			animation.Play("Walk");
			beginTarget.y = transform.position.y;
			transform.LookAt(beginTarget);
			transform.Translate(0, 0, moveSpeed * Time.deltaTime);
		}
	} else {
		transform.rotation.x = 180; //flip us over
		Destroy(gameObject, 2);
	}
}

function PlayerInView(){
	if(target){
		playerDir = target.position - transform.position; 
		var hit : RaycastHit; 
		if (Physics.Raycast (transform.position, playerDir, hit, playerDir.magnitude)) { 
			Debug.DrawLine (transform.position, hit.point, Color.black); 
			if (hit.collider.gameObject.layer == 9) { 
	    		Debug.DrawLine (transform.position, hit.point, Color.red); 
	        	var fov = Vector3.Angle (transform.TransformDirection (Vector3.forward), playerDir);
	        	if (fov < 90) { 
	        		Debug.DrawLine (transform.position, hit.point, Color.yellow); 
	        		if (playerDir.magnitude < range) { 
	        			Debug.DrawLine (transform.position, hit.point, Color.green);
	        			return true;
	        		} 
	        	} 
	      	} 
	  	}
	}	
	return false;
}

function TakeDamage(damage : int){
	health -= damage;
}

function OnCollisionStay(col : Collision) {
	if(col.gameObject.CompareTag("Player")){
		col.gameObject.GetComponent("MouseStats").TakeDamage(damageAmount * Time.deltaTime);
		yield WaitForSeconds(0.5);
		transform.LookAt(beginTarget);
		hiding = 2.0;
	}
	if(col.gameObject.CompareTag("MouseFist") && (target.animation.IsPlaying("Stomp") || target.animation.IsPlaying("RightFist") || target.animation.IsPlaying("LeftJab"))){
		TakeDamage(1);
	}
}

@script RequireComponent(Rigidbody)