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

public class EnemyFactory : MonoBehaviour {

	//Player
	GameObject player;

	//Enemies
	public GameObject squareEnemy;
	public GameObject triangleEnemy;
	public GameObject circleEnemy;
	GameObject[] enemyTypes;

	//Keep track of enemies
	public string[] colorArray = {"red", "blue", "green", "yellow"};
	Dictionary<string, int> numEnemies = new Dictionary<string, int>();

	//Timers for creating them
	int minSpawnTimer = 120;
	int maxSpawnTimer = 360;
	int spawnTimer = 0;

	// Use this for initialization
	void Start () {
		enemyTypes = new GameObject[3];
		enemyTypes[0] = squareEnemy;
		enemyTypes[1] = triangleEnemy;
		enemyTypes[2] = circleEnemy;

		//Create numEnemies dictionary
		numEnemies.Add ("red", 0);
		numEnemies.Add ("blue", 0);
		numEnemies.Add ("green", 0);
		numEnemies.Add ("yellow", 0);


		player = GameObject.Find ("Player");
	}
	
	// Update is called once per frame
	void Update () {
		//Spawn new enemy
		spawnTimer --;
		if(spawnTimer <= 0){
			string color = colorArray[Random.Range (0, colorArray.Length)];
			spawnTimer = Random.Range(minSpawnTimer, maxSpawnTimer);
			spawnEnemy(enemyTypes[Random.Range(0, enemyTypes.Length)], color);
		}

		//Keep at least 1 enemy that is of the player's color on screen at all times
		if(numEnemies[player.GetComponent<PlayerMovement>().getLayerName()] == 0){
			spawnEnemy (enemyTypes[Random.Range(0, enemyTypes.Length)], player.GetComponent<PlayerMovement>().getLayerName());
		}
	}

	void spawnEnemy(GameObject enemy, string color){
		//Starting point - random but not hitting the player
		float tempX;
		float tempZ;
		do{ 
			tempX = Random.Range (-4.5f, 4.5f);
			tempZ = Random.Range (-4.5f, 4.5f);
		} while(Vector3.Distance (new Vector3(player.GetComponent<PlayerMovement>().getLocalX(), 0f, player.GetComponent<PlayerMovement>().getLocalZ()), 
		                          new Vector3(tempX, 0f, tempZ)) < 2);
		enemy.GetComponent<Enemy>().localX = tempX;
		enemy.GetComponent<Enemy>().localZ = tempZ;

		//Keep count of the enemies
		numEnemies[color] ++;

		//Instantiate it
		enemy.transform.position = Vector3.zero;
		enemy.GetComponent<Enemy>().color = color;
		Instantiate(enemy);
	}

	public void enemyKilled(string color){
		numEnemies[color] --;
	}
}
