var police : GameObject;
var range : float = 60.0;
var power : float = 20;
var speed : float = 2.0;
var fireRate : float = 0.1;
var playerLocked : boolean = false;
var radius : float = 85;

private var shotTime : float = 0.0;

function Update () {
	transform.Find("Camera").gameObject.active = playerLocked;
	
	if(playerLocked){
		GameObject.FindWithTag("Player").transform.position = transform.position - transform.forward * 2;
		GameObject.FindWithTag("Player").GetComponent(MouseStats).currentWeapon = "Hands";
	}	
	GetComponent(MouseLook).enabled = playerLocked;
	if(police){ //if there's a bad guy manning the gun
		police.transform.position = transform.position - Vector3.forward * 3;
		if(PlayerInView()){ //if we can see the player
			var rot = Quaternion.LookRotation(GameObject.FindWithTag("Player").transform.position - transform.position);
			transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * speed);
			Fire();
		}		
	} else if(playerLocked){
		if(Input.GetButton("Jump")){
			playerLocked = false;
		}
		if(Input.GetButton("Fire1"))
			Fire();
	}
}

function Fire(){
	if(Time.time > shotTime){
		if(audio)
			audio.Play();
		shotTime = Time.time + fireRate;
		var layerMask = 1 << 2;
		layerMask = ~layerMask;
		var hit : RaycastHit;
		if(Physics.Raycast(transform.position, transform.forward, hit, range, layerMask)){
			hit.transform.gameObject.SendMessage("TakeDamage", power, SendMessageOptions.DontRequireReceiver);
			if(hit.rigidbody){
				hit.rigidbody.AddForce(transform.forward * power * 10 * hit.rigidbody.mass);
			}
			Debug.DrawLine(transform.position, hit.point, Color.white);
		}
	}
}

function PlayerInView(){
	var target = GameObject.FindWithTag("Player").transform;
	if(target){
	playerDir = target.position - transform.position; 
	var hit : RaycastHit;
	var layerMask = 1 << 2;
	layerMask = ~layerMask; 
	if (Physics.Raycast (transform.position, playerDir, hit, playerDir.magnitude, layerMask)) { 
    	Debug.DrawLine (transform.position, hit.point, Color.black); 
    	if (hit.transform.IsChildOf(target)) { 
			Debug.DrawLine (transform.position, hit.point, Color.red); 
    	   	var fov = Vector3.Angle(transform.TransformDirection (Vector3.forward), playerDir);
    	   	if (fov < radius) { 
    	   		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 OnCollisionEnter(col : Collision){
	if(col.gameObject.CompareTag("Player")){
		if(!police)
			playerLocked = true;
	}
}
