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

public class PoacherPoint : Entity {

	public Poacher poacherPrefab; // inspector
	
	private Entity target;

	private bool camping = false;

	private float nextSpawnTimeLeft = 0.0f;

	private List<Poacher> poachers = new List<Poacher>();

	private bool initialized = false;
	
	public void init(Entity target) {
		this.target = target;
		initialized = true;
	}
	
	public void Update() {

		// not initialized - this is a client
		if (!initialized) return;
	
		// calculate the distance from the rhino
		float distance = (target.getLoc () - getLoc ()).magnitude;
		
		// spawn a new camp
		if (!camping && distance <= Data.poacherSpawnDistance && nextSpawnTimeLeft <= 0.0f) {
			
			for (int i = 0; i < Random.Range (10, 17); ++i) {
				spawnPoacher();
			}

			// we got a camping
			camping = true;
		}

		// camping but not chasing
		if (camping && distance <= Data.poacherChaseDistance) {

			// let loose the poachers!
			foreach (Poacher poacher in poachers) {
				poacher.chasing = true;
			}
			poachers.Clear ();

			// no more camping
			camping = false;
			nextSpawnTimeLeft = 10.0f;
		}
	}
	
	public void spawnPoacher() {
		Poacher poacher = Instantiate (poacherPrefab) as Poacher;
		poacher.chasing = false;
		poachers.Add (poacher);
		float angle = Random.Range (0, 2.0f * Mathf.PI);
		float distance = Random.Range (5f, 25.0f);
		Vector2 loc = new Vector2(getLoc().x + distance * Mathf.Cos (angle), getLoc().y + distance * Mathf.Sin (angle));
		poacher.transform.position = new Vector3(loc.x, 0.0f, loc.y);
		poacher.init (target);
	}
}