using UnityEngine;
using System.Collections;

public class AIDirector : MonoBehaviour {

	float waveSpace = 1f;
	float nextWaveIn = 0f;
	int level = 0;
	Vector3 center = new Vector3(989, 700, 1018);
	

	private void Spawn(int amount, string[] colour, string item){
		
		GameObject refer;
		
		switch(item){
			case "droplet":
				refer = (GameObject)(References.dropletObj);
			break;
			case "walker":
				refer = (GameObject)(References.walkerObj);
			break;
			default:
				refer = (GameObject)(References.dropletObj);
			break;
		}
		for(int i=0;i<amount;i++){
			
			if(item == "droplet"){
				Vector3 at = center + RandomPlaceOnCircle(900);
				GameObject mob = Instantiate(refer, at, Quaternion.identity) as GameObject;
				Droplet_S mob_script = mob.GetComponent(typeof(Droplet_S)) as Droplet_S;
				mob_script.SetColour(new LightColour(colour[0]));
				alive++;
			}else if(item == "walker"){
				Vector3 at = center + RandomPlaceOnCircle(900);
				GameObject mob = Instantiate(refer, at, Quaternion.identity) as GameObject;
				Walker_S mob_script = mob.GetComponent(typeof(Walker_S)) as Walker_S;
				mob_script.SetColour(new LightColour(colour[0]), new LightColour(colour[1]));
				alive++;
			}
		}
	}


	Vector3 RandomPlaceOnCircle(float radius){
		//(x-a)^2+(y-b)^2=r^2
		float b = Random.value*(radius*2)-radius;
		
		//a = sqrt(r^2-(y-b)^2)-x
		float a= Mathf.Sqrt(Mathf.Pow(radius, 2) - Mathf.Pow(b, 2));
		
		if(Random.value > 0.5f){
			a *= -1;
		}
		
		return new Vector3(a,0,b);
		
		
		
	}
	 //red blue green magenta yellow cyan orange crimson violet cobalt turquoise lime gray white
	string[] colours = new string[] {"red", "blue", "green", "magenta", "yellow", "cyan", "white", "orange", "crimson", "violet", "cobalt", "turquoise", "lime" };
	float[] weights = new float[]    {13f,     13f,     13f,       7f,             7f,         7f,        10f,      2f,       2f,       2f,     2f,      2f,          2f};
	float weightTotal = 0;
	void Start () {
		foreach(int weight in weights){
			weightTotal += weight;
		}
	}
	static int alive = 0;
	int aliveCap = 75;
	void Update () {
		nextWaveIn -= Time.deltaTime;
		
		if(nextWaveIn <= 0){
			GUIScript.AddScore(10);
			nextWaveIn = waveSpace;
			level++;
			if(alive < aliveCap){
				float randomUnit = Random.value*100f;
				string unit;
				int ncolours;
				if(randomUnit < 90){
					unit = "droplet";
					ncolours = 1;
				}else{
					unit = "walker";
					ncolours = 2;
				}
				
				
				
				string[] sendColours = new string[ncolours];
				
				for(int j = 0; j<ncolours; j++){
					float random = Random.value*weightTotal;
					float weight = 0;
					for(int i = 0; weight < weightTotal; i++){
						weight+= weights[i];
						if (weight > random){
							sendColours[j] = colours[i];
							break;
						}
					}
				}
				Spawn(1, sendColours, unit);
				
					
			}
			
			
			
		}
	}
	static public void DecreaseAlive(){
		alive--;
	}
	
	
}
