using UnityEngine;
using System.Collections;

public class Poacher : Entity {

	public ParticleSystem explosionPrefab; // inspector

	public SlugWalker slugWalker; // inspector

	private Entity target;

	private bool destroying = false;

	private float destroyTime = 60.0f;

	public bool chasing = false;

	public Vector3 lastSendPosition = Vector3.zero; // Last position send to server
	public Quaternion lastRotation = Quaternion.identity;
	private int ID;

	public void init(Entity target) {
		this.ID = networkController.controller.GetNextPoacherID();
		this.target = target;
		networkController.controller.SendSpawnPoacher(this);
	}

	// Update is called once per frame
	void Update () {
		float dt = Time.deltaTime;

		if (!chasing) {
			if (Random.value <= 0.1f) {
				float angle = Random.Range (0, 2.0f * Mathf.PI);
				transform.rotation = Quaternion.identity;
				transform.RotateAround(Vector3.down, angle);
			}
		}

		if (!destroying && chasing) {
		
			// look towards the rhino
			Vector2 diff = target.getLoc () - getLoc ();
			Vector2 dir = diff.normalized;
			float angle = Mathf.Atan2 (dir.y, dir.x);
			transform.rotation = Quaternion.identity;
			transform.RotateAround (Vector3.down, angle);

			// move towards the rhino
			body.velocity = new Vector3 (dir.x * Data.poacherSpeed, 0.0f, dir.y * Data.poacherSpeed);

			// fix y-axis
			fixYAxis ();
		}

		// destroying
		if (destroying) {
			destroyTime -= dt;
			if (destroyTime <= 0.0f) {
				networkController.controller.SendDestroyPoacher (this);
				Destroy (gameObject);
			}
		}
	}

	public void OnCollisionEnter(Collision collision) {
		collision.collider.SendMessage ("OnPoacher", this, SendMessageOptions.DontRequireReceiver);
	}

	public int GetPoacherID() {
		return ID;
	}

	private float minRotate = 0.2f;
	private float maxRotate = 0.4f;

	public void destroy() {
		SoundPlayer.player.PlaySlugHit ();
		networkController.controller.SendKillPoacher (this);
		if (!destroying) {
			body.constraints = RigidbodyConstraints.None;
			body.velocity = new Vector3 (-body.velocity.x * 3.0f, Random.Range (30.0f, 50.0f), -body.velocity.z * 3.0f);
			body.AddTorque (new Vector3 (Random.Range (minRotate, maxRotate), Random.Range (minRotate, maxRotate), Random.Range (minRotate, maxRotate)));
			destroying = true;
			Destroy (slugWalker);
		}

		// spawn an explosion
		ParticleSystem explosion = Instantiate (explosionPrefab) as ParticleSystem;
		explosion.transform.position = transform.position;
	}

	public bool NeedsUpdate() {
		bool needsUpdate = (lastSendPosition - transform.position).sqrMagnitude > 1.0f;
			/*|| ((lastRotation.eulerAngles - transform.rotation.eulerAngles).sqrMagnitude > 1.0f);*/
		return needsUpdate;
	}

	public void UpdateLastSendPosition() {
		lastSendPosition = transform.position;
	}
}
