using UnityEngine;
using System.Collections;

public class CubeSpawner : MonoBehaviour {
	
	public GameObject[] prefabs = new GameObject[7];
	float nextSpawn = 0f;
	float spawnRate = 0.7f;
	int charNumber = 0;
	static int numSpawns = 0;
	static bool spawnMore = false;

    Vector3[] spawnArr = new Vector3[6];
    int spawnLocIndex = 0;
	
	// Use this for initialization
	void Start () {
		print("Spawner started at " + Time.time);
		
		nextSpawn = 0f;
		spawnRate = 0.7f;
		charNumber = 0;
		numSpawns = 0;
		spawnMore = false;
		
        spawnArr[0] = new Vector3(-60.0f, 40.0f, 20.0f);
        spawnArr[1] = new Vector3(0.0f, 40.0f, 20.0f);
        spawnArr[2] = new Vector3(60.0f, 40.0f, 20.0f);
        spawnArr[3] = new Vector3(-60.0f, -40.0f, 20.0f);
        spawnArr[4] = new Vector3(0.0f, -40.0f, 20.0f);
        spawnArr[5] = new Vector3(60.0f, -40.0f, 20.0f);	
	}
	
	// Update is called once per frame
	void Update () {
		print(Global.generation + " ?= 1");
		print(Time.time + " ?> " + nextSpawn);
		print(numSpawns + " ?< " + Global.numOfEachCharacter);
		
		if(Global.generation == 1 && Time.time > nextSpawn && numSpawns < Global.numOfEachCharacter) {

			nextSpawn = Time.time + spawnRate;

            Instantiate(prefabs[charNumber], transform.position, Quaternion.identity);

            charNumber++;

            if ((charNumber) == 7)
            {
                charNumber = 0;
                numSpawns++;
            }
		}
		else if (spawnMore) {
			if( numSpawns < Global.numOfEachCharacter ) {
	            
	            if (!Global.characterExtinct[charNumber])
	            {
	                Instantiate(prefabs[charNumber], spawnArr[spawnLocIndex++], Quaternion.identity);
	                Global.numCharsLeft[charNumber]++;
	            }
	
	            if (spawnLocIndex >= 6)
	                spawnLocIndex = 0;
	
	            charNumber++;
	
	            if ((charNumber) == 7)
	            {
	                charNumber = 0;
	                numSpawns++;
	            }
			} else {
				spawnMore = false;
			}
		}
	}
	
	public static void SpawnNewRound() 
	{
		spawnMore = true;
		numSpawns = 0;
		if(Global.generation > 3)
			Global.numOfEachCharacter--;
		
	}
}
