var speed:int;

var currentSpeed:int;

var leftMost:float;
var rightMost:float;
var topMost:float;
var bottomMost:float;

var stickBall = new Hashtable();
var ball:Rigidbody;

var metalBrick:Rigidbody;
var woodBrick:Rigidbody;
var rubberBrick:Rigidbody;
var iceBrick:Rigidbody;

var enemyBricks = [];
var totalBricks:int = 0;

var sqlClass:sqlClass;

var pause:boolean = false;

var speedStick:boolean = false;
var slowStick:boolean = false;
var originalColor:Color;

var nameStyle:GUIStyle;
var scoreStyle:GUIStyle;
var levelStyle:GUIStyle;

var userSaves = new Array();
var showSaves:boolean = false;
var loadTexture:Texture2D;
var loadStyle:GUIStyle;

function Start () {
	yield initializeScreenBounderies();
	var menu:mainMenuController;
	menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
	
	var player = menu.player;
	if(player.getState()=='new'){
		initializeLevel(player.getLevel());
	}else if(player.getState()=='load'){
		var childCylinder = GameObject.FindGameObjectsWithTag('childCylinder');
		totalBricks = player.loadLevel(player.getData(), rubberBrick, iceBrick, woodBrick, metalBrick, ball, this.gameObject.rigidbody, childCylinder);
	}
	
	yield speedOfStick();
}

function Update () {
	if(Input.GetKey(KeyCode.LeftArrow)||Input.GetKey(KeyCode.RightArrow)){
		transform.Translate(Vector3.right * currentSpeed * Input.GetAxis('Horizontal') * Time.deltaTime);
	}
	
	
	if((transform.position.x-(this.gameObject.collider.bounds.size.x)/1.5)<=leftMost || (transform.position.x+(this.gameObject.collider.bounds.size.x)/4)>=rightMost){
		if((transform.position.x-(this.gameObject.collider.bounds.size.x))<=leftMost && Input.GetKey(KeyCode.LeftArrow)){
			currentSpeed = 0;
		}
		else if((transform.position.x+(this.gameObject.collider.bounds.size.x))>=rightMost && Input.GetKey(KeyCode.RightArrow)){
			currentSpeed = 0;
		}
		else{
			if(Input.GetKeyUp(KeyCode.LeftArrow)){
				currentSpeed=0;
			}else if(Input.GetKeyUp(KeyCode.RightArrow)){
				currentSpeed = 0;
			}
			else if(Input.GetKey(KeyCode.LeftArrow)||Input.GetKey(KeyCode.RightArrow)){
				currentSpeed = speed;
			}
		}
	}else{
		currentSpeed = speed;
	}	
	
	
	//Pause
	if(Input.GetKeyDown(KeyCode.P)){
		pauseGame();
	}
	
	//Save State
	if(Input.GetKeyDown(KeyCode.F5)){
		storeState();		
	}
	
	//Load Saves
	if(Input.GetKeyDown(KeyCode.L)){
		//Pause Game
		pauseGame();
		
		getUserSaves();
	}
	
	//Exit Game
	if(Input.GetKeyDown(KeyCode.Q)){
		Application.Quit();
	}
	
	
	var menu:mainMenuController;
	menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
	
	var player = menu.player;
	
	var removeBall = Array();
	
	//Check ball/s position	
	var allBalls:Hashtable;
	allBalls = getBallObjects();
	
	if(allBalls!=null){
		for(var b:GameObject in allBalls.Keys){
			if(b.transform.position.y<bottomMost){				
				if(allBalls.Count<2){
					//Store Score
					sqlClass = new sqlClass('arkanoid');
					sqlClass.storeHighScore(player.getName(), player.getScore());
					
					removeBall.Add(b);
					mainMenuController.gameOver = true;				
					//GameOver
					Application.LoadLevel(0);
				}else{
					removeBall.Add(b);
				}
			}
			//Check the speeds
			if(b.rigidbody.velocity.y>=50||b.rigidbody.velocity.y<=-50){
				//Reduce Speed
				if(b.rigidbody.velocity.y>=50){
					b.rigidbody.velocity.y = 40;
				}else{
					b.rigidbody.velocity.y = -40;
				}
				
			}
			
		}
	}
	
	
	//Stick any to stick balls
	if(stickBall!=null){
		for(var s:GameObject in stickBall.Keys){
			s.transform.position.x = (this.gameObject.transform.position.x)-((this.gameObject.collider.bounds.size.x)/4);
			s.transform.position.y = (this.gameObject.transform.position.y)+(this.gameObject.collider.bounds.size.y);
		}
	}
	
	
	//Remove from HashTable
	if(removeBall!=null){
		for(var r=0; r<removeBall.length; r++){
			var gameBall:GameObject = removeBall[r];
			
			player.removeBall(gameBall);
			Destroy(gameBall);
		}
	}
	
}

function FixedUpdate(){
	if(Input.GetKey(KeyCode.Space)||Input.GetKey(KeyCode.KeypadEnter)){
		jumpBall();
	}	
}

function updateTotalBrickNumber(){
	totalBricks--;
	
	if(totalBricks<1){
		var menu:mainMenuController;
		menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
		
		var player = menu.player;
		player.incrementLevel();
		
		//Remove All ball/s position	
		var allBalls:Hashtable;
		allBalls = getBallObjects();
		
		var removeBall = Array();
		for(var b:GameObject in allBalls.Keys){
			removeBall.Add(b);
		}	
		
		//Remove from HashTable
		for(var r=0; r<removeBall.length; r++){
			var gameBall:GameObject = removeBall[r];
			
			player.removeBall(gameBall);
			Destroy(gameBall);
		}
		
		//Store High Score
		sqlClass = new sqlClass('arkanoid');
		sqlClass.storeHighScore(player.getName(), player.getScore());
		
		player.setState('new');
		Application.LoadLevel(player.getLevel());
	}
}
	
function initializeLevel(level){
	//Create ball
	var ballg:Rigidbody;
	ballg = Instantiate(ball, Vector3(-0.165, -7, 0), Quaternion.identity);
	//Stick the ball
	stickTheBall(ballg.gameObject);

	var metalSizeX = metalBrick.renderer.bounds.size.x;
	var metalSizeY = metalBrick.renderer.bounds.size.y;
	var metalCount = 0;
	
	var woodSizeX = woodBrick.renderer.bounds.size.x;
	var woodSizeY = woodBrick.renderer.bounds.size.y;
	var woodCount = 0;
	
	var rubberSizeX = rubberBrick.renderer.bounds.size.x;
	var rubberSizeY = rubberBrick.renderer.bounds.size.y;
	var rubberCount = 0;
	
	var iceSizeX = iceBrick.renderer.bounds.size.x;
	var iceSizeY = iceBrick.renderer.bounds.size.y;
	var iceCount = 0;
		
	totalBricks = 0;
	if(level==1){
		//Create RubberBricks
		for(var r=1; r<=4; r++){
			rubberCount=0;
			do{		
				//Start From LeftMost
				var rubberPositionX = (leftMost+10/*to test use this: 25*/) + (rubberSizeX*rubberCount);
				var rubberPositionY = (topMost-2) - (rubberSizeY*r);
				
				Instantiate(rubberBrick, Vector3(rubberPositionX, rubberPositionY, 0), Quaternion.identity);
				rubberCount++;
				totalBricks++;		
			}while(rubberPositionX<(rightMost-10/*to test use this: 25*/));
		}
	}else if(level==2){
		for(r=1; r<=4; r++){
			iceCount=0;
			do{		
				//Start From LeftMost
				var icePositionX = (leftMost+10/*to test use this: 25*/) + (iceSizeX*iceCount);
				var icePositionY = (topMost-2) - (iceSizeY*r);
				
				Instantiate(iceBrick, Vector3(icePositionX, icePositionY, 0), Quaternion.identity);
				iceCount++;	
				totalBricks++;	
			}while(icePositionX<(rightMost-10/*to test use this: 25*/));
		}
	}else if(level==3){
		for(r=1; r<=4; r++){
			woodCount=0;
			do{		
				//Start From LeftMost
				var woodPositionX = (leftMost+10/*to test use this: 25*/) + (woodSizeX*woodCount);
				var woodPositionY = (topMost-2) - (woodSizeY*r);
				
				Instantiate(woodBrick, Vector3(woodPositionX, woodPositionY, 0), Quaternion.identity);
				woodCount++;	
				totalBricks++;	
			}while(woodPositionX<(rightMost-10/*to test use this: 25*/));
		}
	}else if(level==4){
		for(r=1; r<=4; r++){
			metalCount=0;
			do{		
				//Start From LeftMost
				var metalPositionX = (leftMost+10/*to test use this: 25*/) + (metalSizeX*metalCount);
				var metalPositionY = (topMost-2) - (metalSizeY*r);
				
				Instantiate(metalBrick, Vector3(metalPositionX, metalPositionY, 0), Quaternion.identity);
				metalCount++;	
				totalBricks++;	
			}while(metalPositionX<(rightMost-10/*to test use this: 25*/));
		}
	}
	
}

function OnGUI(){
	var menu:mainMenuController;
	menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
	
	var player = menu.player;
	
	GUI.Label(Rect(10,10,250, 30), player.getName(), nameStyle);
	GUI.Label(Rect((Screen.width/2)-75, 10, 150, 30), 'Score: ' + player.getScore(), scoreStyle);
	GUI.Label(Rect((Screen.width)-85, 10, 150, 30), 'Level: ' + player.getLevel(), levelStyle);
	
	if(showSaves){
		GUI.DrawTexture (Rect(100, 100, (Screen.width-150), (Screen.height-150)), loadTexture);
		showUserSaves();
		//Close button
		if(GUI.Button(Rect(((Screen.width-80)), 100, 30, 30),  'X')){
			//Hide Load Menu
			showSaves = false;
			
			//Unpause Game
			pauseGame();
		}
	}
}

function initializeScreenBounderies(){
	leftMost = Camera.main.ScreenToWorldPoint(Vector3(0, 0, 0)).x;
	rightMost = Camera.main.ScreenToWorldPoint(Vector3(Screen.width, 0, 0)).x;
	topMost = Camera.main.ScreenToWorldPoint(Vector3(0, Screen.height, 0)).y;
	bottomMost = Camera.main.ScreenToWorldPoint(Vector3(0, 0, 0)).y;
		
	
	//Set Wall Position with Screen Size
	var lWall = GameObject.FindGameObjectWithTag('leftwall');
	lWall.transform.position.x = leftMost;
	
	var rWall = GameObject.FindGameObjectWithTag('rightwall');
	rWall.transform.position.x = rightMost;
	
	var tWall = GameObject.FindGameObjectWithTag('topwall');
	tWall.transform.position.y = topMost;
	
	currentSpeed = speed;
	
	//Store original color
	var childCylinder = GameObject.FindGameObjectsWithTag('childCylinder');
	for(var child in childCylinder){
		originalColor = child.gameObject.renderer.material.color;
	}
	
	yield;
}

function jumpBall(){
	var toRemove = Array();
	
	for(var s:GameObject in stickBall.Keys){		
		if(s.transform.position.y == ((this.gameObject.transform.position.y)+(this.gameObject.collider.bounds.size.y)))
		{			
			toRemove.Add(s);
			break;
		}		
	}
	
	for(var r = 0; r<toRemove.length; r++){
		var ballObject:GameObject = toRemove[r];
		stickBall.Remove(ballObject);
		ballObject.GetComponent(Rigidbody).AddForce(Vector3.up * 100 * 30);
	}
			
}

function stickTheBall(gameObject:GameObject){
	if(!stickBall.ContainsKey(gameObject))
		stickBall.Add(gameObject, true);
}

function speedUpStick(){
	speedStick = true;
}

function slowDownStick(){
	slowStick = true;	
}

function speedOfStick(){
	while(true){
		var childCylinder = GameObject.FindGameObjectsWithTag('childCylinder');
		if(speedStick){
			speed*=2;
			//Change the children's color
			childCylinder = GameObject.FindGameObjectsWithTag('childCylinder');
			for(var child in childCylinder){
				child.gameObject.renderer.material.color = Color.red;
			}
			yield WaitForSeconds(3);
			speedStick = false;
		}else if(slowStick){
			speed/=2;
			//Change the children's color
			childCylinder = GameObject.FindGameObjectsWithTag('childCylinder');
			for(var child in childCylinder){
				child.gameObject.renderer.material.color = Color.magenta;
			}
			yield WaitForSeconds(3);
			slowStick = false;
		}else if(!speedStick && !slowStick){
			speed=30;
			childCylinder = GameObject.FindGameObjectsWithTag('childCylinder');
			//Change back to normal color
			for(var child in childCylinder){
				child.gameObject.renderer.material.color = originalColor;
			}
			yield;
		}
		
	}
}

function getBallObjects(){
	var menu:mainMenuController;
	menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
	
	var player = menu.player;
	var balls = Hashtable();
	balls = player.getBalls();
	return balls;
}

function OnCollisionExit(otherObject:Collision){
	if(otherObject.transform.tag=='ball'){
		otherObject.gameObject.GetComponent(Rigidbody).AddForce(Vector3.up * 30);
		otherObject.gameObject.GetComponent(Rigidbody).AddForce(Vector3(this.gameObject.rigidbody.velocity.x,0,0));
	}
}

function storeState(){
	//Get all the gameobject
	var allObjects = new Array(); 
	allObjects = Resources.FindObjectsOfTypeAll(typeof(GameObject));	
	
	var menu:mainMenuController;
	menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
	
	var player = menu.player;
	
	//Get player details
	var playerName = player.getName();
	var playerScore = player.getScore();
	var playerLevel = player.getLevel();
	
	var playerDetails = new Array(playerName, playerScore, playerLevel);
	
	sqlClass = new sqlClass('arkanoid');
	sqlClass.saveState(playerDetails, allObjects);
}

function getUserSaves(){
	var menu:mainMenuController;
	menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
	
	var player = menu.player;
	
	sqlClass = new sqlClass('arkanoid');
	userSaves = sqlClass.getUserSaves(player.getName());
	showSaves = true;
}

function showUserSaves(){
	GUI.Label(Rect((Screen.width/2-60), 120, 120, 30), 'Load State', loadStyle);
	var count = 0;
	for(var s in userSaves){
		count++;
		if(GUI.Button(Rect((120),(120+(count*60)), ((Screen.width-150)-40), 30), "Level: "+s[3]+" Score: "+s[2]+" "+s[4])){
			loadLevel(s[0].ToString(), parseInt(s[3]), parseInt(s[2]));
		}
		
	}
}

function loadLevel(id:String, level:int, score:int){
	sqlClass = new sqlClass('arkanoid');
	var gameObjects = sqlClass.loadState(id);
	var menu:mainMenuController;
	menu = GameObject.FindGameObjectWithTag('menuSetting').GetComponent(mainMenuController);
	
	var player = menu.player;
	
	player.setState('load');
	player.setScore(score);
	player.setLevel(level);
	
	//Remove All ball/s position	
	var allBalls:Hashtable;
	allBalls = getBallObjects();
	
	var removeBall = Array();
	for(var b:GameObject in allBalls.Keys){
		removeBall.Add(b);
	}	
	
	//Remove from HashTable
	for(var r=0; r<removeBall.length; r++){
		var gameBall:GameObject = removeBall[r];
		
		player.removeBall(gameBall);
		Destroy(gameBall);
	}
	
	//Store Data to Load
	player.holdData(gameObjects);
	
	//unpause
	pauseGame();
	Application.LoadLevel(level);
	
}

function pauseGame(){
	if(!pause){
		Time.timeScale = 0;
		pause = true;
	}else{
		Time.timeScale = 1;
		pause = false;
	}
}

