#pragma strict

var sezioni : GameObject[] = new GameObject[20];

var materialPieno : Material;
var materialVuoto : Material;

var joystickPlayer : JoystickManager;

var someoneIsPlaying = false;
var endGame = false;

var index = 0;

var turno = 1;
var maxTurni = 5;

var timerText : GameObject;
var arrows : GameObject;

var direction;
var oldDirection = 'right';

var gameMusicIsPlaying = false;

function Start () {
	InvokeRepeating("Tick", 0, 1.0f);
	
	for(var i = 0; i < 20; i++) {
		sezioni[i].renderer.material = materialPieno;
	}
	
	joystickPlayer = new JoystickManager();
}

function Update () {
	
}

function Tick() {

	if(someoneIsPlaying) {
	
		if(!gameMusicIsPlaying) {
		
			gameMusicIsPlaying = true;
			GameObject.Find("Camera1").GetComponent(MusicScript).StartMusic();
		
		}
	
		sezioni[index].renderer.material = materialVuoto;
		index++;
		
		var countLeft = 0;
		var countRight = 0;
		
		for(var j = 1; j < 5; j++) {
			if(joystickPlayer.GetTrigger(j) < -0.5f) {
				countRight++;
				Debug.Log(joystickPlayer.GetTrigger(j));
			} else if(joystickPlayer.GetTrigger(j) > 0.5f) {
				countLeft++;
			}
		}
		
		if(countRight > countLeft) {
			direction = 'right';
			if(direction != oldDirection) {
				arrows.GetComponent(ArrowRotate).ChangeDir(direction);
			}
		} else {
			direction = 'left';
			if(direction != oldDirection) {
				arrows.GetComponent(ArrowRotate).ChangeDir(direction);
			}
		}
		
		oldDirection = direction;
		
		if(index == 20) {
		
			turno++;
			
			timerText.GetComponent(TextMesh).text = "" + (maxTurni - turno);
			
			IncreseDifficulty();
			
			if(turno == maxTurni) {
				Debug.Log("Yeeeeeeeeeeeeeeeeeeeeeeeeeee!");
				
				someoneIsPlaying = false;
				endGame = true;
			}
		
			
			
			Debug.Log("Cambio!!!");
			
			var enemySpawners = GameObject.FindGameObjectsWithTag("EnemySpawners");
			for(var enemySpawner : GameObject in enemySpawners) {
				enemySpawner.GetComponent(EnemySpawner).ChangeColour(direction);
			}
			
			index = 0;
			
			for(var i = 0; i < 20; i++) {
				sezioni[i].renderer.material = materialPieno;
			}
		}
	}
	
	if(endGame) {
	
		var pannelli = GameObject.FindGameObjectsWithTag("Pannelli");
		for(var pannello in pannelli) {
		
			pannello.GetComponent(JoinGame).EndGame();
		
		}
	
	}
}

function IncreseDifficulty() {

	var enemySpawners = GameObject.FindGameObjectsWithTag("EnemySpawners");
	for(var enemySpawner : GameObject in enemySpawners) {
		enemySpawner.GetComponent(EnemySpawner).enemySpeed += 0.5f;
		enemySpawner.GetComponent(EnemySpawner).enemyProjectileSpeed += 0.25f;
		enemySpawner.GetComponent(EnemySpawner).spawnFilter -= 0.02f;
	}

}