#pragma strict
var crosshairTexture : Texture2D;
var crosshairTextureRed: Texture2D;
var btnTexture : Texture2D;
var isEnemy: boolean;
var bulletsTex: Texture2D;
var numBullets: int;
var ammoBox: Rigidbody2D;
var fireBall: Rigidbody2D;
var miniFireBall:Rigidbody2D;
var highScore:int;
var db : dbAccess;
var firstName: String;
var bulletsCount:int;
var targetCount:int;
var startTime: float;
var textTime : String;
var target: Rigidbody2D;
var saveHighScore:int;
var timeInt:int;
var guiTime:float;
var level:int;
var List=new Array();
var loaded: int;
var mySkin: GUISkin;
var btnResult: boolean;

function Start (){
	loaded = 0;
	isEnemy = false;	
	GetSaveScore();
	
	if(numBullets == 0){
		numBullets = 10;
	}
		
	if(Application.loadedLevel == 2 && loaded == 0){
		targetCount = 10;
    }else if(Application.loadedLevel == 3 && loaded == 0){
		targetCount = 11;
	}else if(Application.loadedLevel == 4 && loaded == 0){
		targetCount = 12;
	}else if(Application.loadedLevel == 5 && loaded == 0){
		targetCount = 13;
	}
	
	
	if(Application.loadedLevel != 0 && Application.loadedLevel != 1 && Application.loadedLevel != 6 && Application.loadedLevel != 7){
		yield GenerateAmmoBox();
		yield GenerateFireBall();
	}
}

function Update () {
	if(Application.loadedLevel != 0 && Application.loadedLevel != 1 && Application.loadedLevel != 6 && Application.loadedLevel != 7){
		startTime -= Time.deltaTime;
	}
	
    Screen.showCursor = false;
	var hit: RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
	
	if (hit.collider != null){
		if(hit.transform.tag == "Target"){
        	isEnemy = (hit.transform.tag == "Target");// assign the comparison result to is enemy
        }else if(hit.transform.tag == "Play"){
        	isEnemy = (hit.transform.tag == "Play");
        }else if(hit.transform.tag == "HighScore"){
        	isEnemy = (hit.transform.tag == "HighScore");
        }else if(hit.transform.tag == "Quit"){
        	isEnemy = (hit.transform.tag == "Quit");
        }else if(hit.transform.tag == "Ok"){
        	isEnemy = (hit.transform.tag == "Ok");
        }else if(hit.transform.tag == "HighScoreOk"){
        	isEnemy = (hit.transform.tag == "HighScoreOk");
		}else if(hit.collider.tag == "EntryOk"){
			isEnemy = (hit.transform.tag == "EntryOk");
		}else if(hit.collider.tag == "Load"){
			isEnemy = (hit.transform.tag == "Load");
		}else if(hit.collider.tag == "FireBall"){
			isEnemy = (hit.transform.tag == "FireBall");
		}
    }
    else{
    	isEnemy = false;
    }
    
    if (Input.GetMouseButtonDown(0)) {    	
        if (hit.collider != null) {     
        	if(numBullets >= 1 && Application.loadedLevel != 0 && Application.loadedLevel != 1 && Application.loadedLevel != 6 && Application.loadedLevel != 7){    
	            if (hit.collider.tag == "Target") { 
	            	numBullets--;
	            	highScore += 2;	
	            	targetCount--;         	      	
	               	Destroy(hit.collider.gameObject);
        		}else if(hit.collider.tag == "FireBall")
        		{
        			numBullets--;
        			highScore += 10;
        			Destroy(GameObject.FindGameObjectWithTag("FireBall"));
        				for(var i = 0; i < 3; i++){
        					var ranX = Random.Range(-5,5);
        					GameObject.Instantiate(miniFireBall,Vector3(ranX,10,5), Quaternion.identity);
        				}	
        		}

            }
            else{
	            if(hit.collider.tag == "Play"){
	            	Application.LoadLevel(2);
	            }else if(hit.collider.tag == "HighScore"){
	            	Application.LoadLevel(7);  
	            }else if(hit.collider.tag == "Quit"){
	            	btnResult = true;
	            }else if(hit.collider.tag == "Ok"){
	            	SaveScore();
	            	db.insertNewPlayer(firstName);
            		Application.LoadLevel(1);         	
	            }else if(hit.collider.tag == "HighScoreOk"){
	            	Application.LoadLevel(1);  
	            }else if(hit.collider.tag == "EntryOk"){
    				db.insertPlayerScore(firstName, highScore);
    				Application.LoadLevel(1);
	            }else if(hit.collider.tag == "Load"){
	            	loadGame();	            	
	            }
            }
         }else{
	     	if(Application.loadedLevel != 0 && Application.loadedLevel != 1 && Application.loadedLevel != 6 && Application.loadedLevel != 7){
		    	numBullets--; 
			}
         }
         
    }
    
    if(bulletsCount == 2 && numBullets == 0 && targetCount != 0){
    	SaveScore();
    	Application.LoadLevel(6);
    }else if(Application.loadedLevel == 2 && targetCount == 0){
		SaveScore();
    	Application.LoadLevel(3);
    }else if(Application.loadedLevel == 3 && targetCount == 0){
    	Application.LoadLevel(4);
    	SaveScore();
	}else if(Application.loadedLevel == 4 && targetCount == 0){
    	Application.LoadLevel(5);
    	SaveScore();
	}else if(Application.loadedLevel == 5 && targetCount == 0){
		SaveScore();
    	Application.LoadLevel(6);
    }else if(startTime <= 0){
    	SaveScore();
    	Application.LoadLevel(6);
    }else if(Input.GetKeyDown(KeyCode.Escape)){
    	PlayerPrefs.DeleteAll();
    	Application.Quit();
    }else if(Input.GetKeyDown(KeyCode.S)){
    	saveGame();
    }
}

public function IncreaseBullets(num:int){
	numBullets += num;
}

public function DecreaseTarget(numT:int){
	targetCount -= numT;
}
 
function OnGUI () 
{
	GUI.skin = mySkin;
	var textStyle = new GUIStyle(GUI.skin.label);
	
	var cross = crosshairTexture;
	if(isEnemy == true){
		cross = crosshairTextureRed;
	}
    var mousePos = Event.current.mousePosition;
 
    mousePos.x = Mathf.Clamp(mousePos.x, 0, 3000);
    mousePos.y = Mathf.Clamp(mousePos.y, 0, 3000);
 
    GUI.DrawTexture( Rect( mousePos.x - (cross.width/10),
                           mousePos.y - (cross.height/10),
                           cross.width/5,
                           cross.height/5), cross);
    
    if(Application.loadedLevel != 0 && Application.loadedLevel != 1 && Application.loadedLevel != 6 && Application.loadedLevel != 7){                       
	    for(var i=0;i<numBullets;i++){
	       GUI.DrawTexture (Rect(10+i*bulletsTex.width/10,10,bulletsTex.width/10,bulletsTex.height/10) ,bulletsTex,ScaleMode.StretchToFill,true);   
		}  
		
		GUI.Label(Rect(400,8,100,80),"High Score: " + highScore);      
		GUI.Label(Rect(500,8,80,20),"Target: " + targetCount); 
		
		var minutes : int = startTime / 60;
   		var seconds : int = startTime % 60;
   		var fraction : int = (startTime * 100) % 100;
 
   		textTime = String.Format ("{0:00}:{1:00}:{2:00}", minutes, seconds, fraction); 
   		GUI.Label (Rect (400, 25, 100, 30), textTime);    
	}else if(Application.loadedLevel == 0){
	    firstName = GUI.TextField(Rect(700, 250, 200, 20),firstName, 25);
	}else if(Application.loadedLevel == 6){
		GUI.Label(Rect(700,300,200,20),"High Score: " + highScore,textStyle);
	}   
	
	if(Application.loadedLevel == 1){
		if(btnResult == true){
			GUI.Window(1,Rect (700,100,300,50),Dialog, "Are you sure you want to quit?");
		}
	    
	}
}

function Dialog(windowID : int) {
	Screen.showCursor = true;
	if (GUI.Button (Rect (10,20,100,20), "Yes"))
	{
    	PlayerPrefs.DeleteAll();
    	Application.Quit();
	}else if(GUI.Button (Rect (150,20,100,20), "No")){
		Application.LoadLevel(1);
	}
	
}

function SaveScore()
{   
	PlayerPrefs.SetInt("saveHighScore", highScore);  
	PlayerPrefs.SetFloat("saveTime", startTime);  
	PlayerPrefs.SetString("saveName", firstName);  
	PlayerPrefs.SetInt("loaded",0); 
}

function GetSaveScore()
{    
	firstName = PlayerPrefs.GetString("saveName"); 
	loaded = PlayerPrefs.GetInt("loaded");
	
	highScore = PlayerPrefs.GetInt("saveHighScore");
	startTime = PlayerPrefs.GetFloat("saveTime"); 
	if(startTime <= 0){
		startTime = 45;
	}

	if(loaded == 1){ 
		targetCount = PlayerPrefs.GetInt("saveTargetCount");  
		numBullets = PlayerPrefs.GetInt("saveBullets");  
		PlayerPrefs.SetInt("loaded",0); 
	}
}

function GetSavedFirstName():String{
	firstName = PlayerPrefs.GetString("saveName"); 
	return firstName;
}

function GetSavedTarget(): int{	
	loaded = PlayerPrefs.GetInt("loaded");
	if(loaded == 1){
		targetCount = PlayerPrefs.GetInt("saveTargetCount"); 
		return targetCount;
	}
	else{
		return targetCount;
	}
}

function saveGame(){
	level = Application.loadedLevel;
	PlayerPrefs.SetInt("saveHighScore", highScore);  
	PlayerPrefs.SetFloat("saveTime", startTime);  
	PlayerPrefs.SetString("saveName", firstName);
	PlayerPrefs.SetInt("saveTargetCount", targetCount);  
	PlayerPrefs.SetInt("saveBullets",numBullets);  
	PlayerPrefs.SetInt("saveLevel",level); 
	db.SaveGameState(firstName, highScore,level,targetCount,startTime,numBullets);
}

function loadGame(){
	List = db.LoadGameState(firstName);
	
	if(List != null){
		highScore = parseInt(List[0].ToString());
		level = parseInt(List[1].ToString()); 
		targetCount = parseInt(List[2].ToString()); 
		startTime = parseFloat(List[3].ToString()); 	
		numBullets = parseInt(List[4].ToString()); 
		
		PlayerPrefs.SetInt("saveHighScore", highScore);  
		PlayerPrefs.SetFloat("saveTime", startTime);  
		PlayerPrefs.SetString("saveName", firstName);
		PlayerPrefs.SetInt("saveTargetCount", targetCount);  
		PlayerPrefs.SetInt("saveBullets",numBullets); 
		PlayerPrefs.SetInt("loaded",1); 
		Application.LoadLevel(level);
	}
	
	
}

function GenerateAmmoBox(){
	var randomPos = Random.Range(-5,5);
	var numberOfSec = 5;
	for(var i = 0; i < 2; i++){
		yield WaitForSeconds(numberOfSec);
		GameObject.Instantiate(ammoBox,Vector3(randomPos,10,5), Quaternion.identity);	
		bulletsCount++;
		numberOfSec += 5;
	}
}

function GenerateFireBall(){
	if(Application.loadedLevel == 3){
		var randomPos = Random.Range(-5,5);
		GameObject.Instantiate(fireBall,Vector3(randomPos,10,5), Quaternion.identity);
		yield WaitForSeconds(1);
	}
}



