using UnityEngine;
using System.Collections;

public class Game : MonoBehaviour {
	public enum STATES{
		MENU,
		JEU,
		SCORE,
		AIDE,
		PAUSE,
		EXPLICATION,
		VICTOIRE,
		DEFAITE,
		INITIALISATION,
		SELECTIONARME
	};
	public static Game instance;

	public int compteurpoints;
	public int nbvie;
	public int niveauMax = 2;
	public int niveau;
	public int nbEnnemiTue;
	public int score ;
	public int[] pointNecessaire = {2,5,10};
	public STATES state = STATES.MENU;

	public GameObject PlaceArme;
	public GameObject placementTourelle1;
	public GameObject placementTourelle2;
	public GameObject niveau1,niveau2;
	public GameObject cam1,cam2,mainCam;
	public GameObject[] ennemi;
	public GameObject[] tour;
	public GameObject[] respawn1,respawn2;

	private int choixarme;
	private float compteur,compteurmax;
	private int nbRespawn;
	private int compteurTemps;

	public Texture2D[] textureBoutonTourelle;
	public Texture2D texturePageAccueil;
	public Texture2D[] texturePage;
	public Texture2D[] textureBouton;

	public GUISkin skin1;

	void Start () {
		//PlayerPrefs.SetInt("highScore", 0);
		instance = this;
		nbEnnemiTue = 0;
		choixarme = 1;
		compteurmax = 240.0f;
		niveau = 1;
		score = 0;
	}

	void OnGUI (){
		GUI.skin=skin1;
		switch (state) {
			case STATES.MENU:
				OnGUImenu ();
				break;
			case STATES.AIDE:
				OnGUIoption ();
				break;
			case STATES.EXPLICATION:
				OnGUIexplication ();
				break;
			case STATES.DEFAITE:
				OnGUIdefaite ();
				break;
			case STATES.PAUSE:
				OnGUIpause ();
				break; 
			case STATES.SCORE:
				OnGUIscore ();
				break;
			case STATES.VICTOIRE:
				OnGUIvictoire ();
				break;
			case STATES.JEU:
				OnGUIjeu ();
				break;
			case STATES.SELECTIONARME:
				OnGUIselectionarme ();
				break;
		}
	}

	void OnGUImenu (){
		GUI.DrawTexture (new Rect(0,0,Screen.width,Screen.height),texturePageAccueil);

		if (GUI.Button (MyRect(50, 175, 150, 50), "Lancer le jeu")){
			state=STATES.EXPLICATION;
		}
		if (GUI.Button (MyRect (50, 230, 150, 50), "Aide")){
			state=STATES.AIDE;
		}
		if (GUI.Button (MyRect (50, 285, 150, 50), "Quitter")){
			Application.Quit();
		}
	}

	void OnGUIoption (){
		GUI.DrawTexture (new Rect(0,0,Screen.width,Screen.height),texturePage[0]);

		if (GUI.Button (MyRect (635, 20, 150, 50), "Lancer le jeu")){
			state=STATES.EXPLICATION;
		}		
		if (GUI.Button (MyRect (635, 75, 150, 50), "Menu")){
			state=STATES.MENU;
		}
	}

	void OnGUIexplication (){
		GUI.DrawTexture (new Rect(0,0,Screen.width,Screen.height),texturePage[0]);

		if (GUI.Button (MyRect (635, 20, 150, 50), "Lancer le jeu")){
			state=STATES.INITIALISATION;
		}
	}

	void OnGUIdefaite (){
		GUI.DrawTexture (new Rect(0,0,Screen.width,Screen.height),texturePage[1]);

		GUI.Label (MyRect (10, 120, 500, 100), "Vous avez echoué au niveau " + niveau.ToString()+" !");
		GUI.Label (MyRect (10, 140, 600, 100), "Vous avez tué "+nbEnnemiTue.ToString()+" ennemis depuis le début de la partie !");

		if (GUI.Button (MyRect (630, 420, 150, 50), "Score")){
			state=STATES.SCORE;
		}
	}

	void OnGUIpause(){
		if (GUI.Button (MyRect (100, 10, 150, 50), "Menu")){
			Time.timeScale = 1;
			alldestruction ();
			if (niveau==1){
				niveau1.SetActive(false);
			}
			else{
				niveau2.SetActive(false);
			}	
			StopCoroutine("ajoutPoint");
			StopCoroutine("CreationEnnemi");
			destructionRespawn();
			niveau=1;
			nbEnnemiTue = 0;
			score = 0;
			mainCam.SetActive(true);
			state=STATES.MENU;
		}
		if (GUI.Button (MyRect (260, 10, 150, 50), "Retour au jeu")){
			Time.timeScale =1;
			state=STATES.JEU;
		}
	}

	void OnGUIscore (){
		GUI.DrawTexture (new Rect(0,0,Screen.width,Screen.height),texturePage[2]);

		if (PlayerPrefs.GetInt("highScore")!=0){
			GUI.Label (MyRect (10, 100, 500, 100), "Votre highscore est de " + PlayerPrefs.GetInt("highScore").ToString()+" !");
		}

		GUI.Label (MyRect (10, 130, 500, 100), "Vous avez un score de " + score.ToString()+" !");

		if (GUI.Button (MyRect (480, 410, 150, 50), "Recommencer le jeu")){
			if (score>PlayerPrefs.GetInt("highScore")){
				PlayerPrefs.SetInt("highScore", score);
				PlayerPrefs.Save();
			}
			niveau=1;
			score = 0;
			state=STATES.INITIALISATION;
		}
		if (GUI.Button (MyRect (640, 410, 150, 50), "Menu")){
			if (score>PlayerPrefs.GetInt("highScore")){
				PlayerPrefs.SetInt("highScore", score);
				PlayerPrefs.Save();
			}
			niveau=1;
			nbEnnemiTue = 0;
			score = 0;
			state=STATES.MENU;
		}
	}
	
	void OnGUIvictoire (){
		GUI.DrawTexture (new Rect(0,0,Screen.width,Screen.height),texturePage[3]);

		GUI.Label (MyRect (10, 10, 500, 100), "Vous avez reussi le niveau " + niveau.ToString()+" !");
		GUI.Label (MyRect (10, 50, 500, 100), "Vous avez tué "+nbEnnemiTue.ToString()+" ennemis depuis le début de la partie !");

		if (GUI.Button (MyRect (640,410, 150, 50), "Score")){
			score+=compteurpoints;
			state=STATES.SCORE;
		}
		if (niveau<niveauMax){
			if (GUI.Button (MyRect (480, 410, 150, 50), "Niveau suivant")){
				niveau++;
				score+=compteurpoints;
				state=STATES.INITIALISATION;
			}
		}
	}

	void OnGUIjeu (){
		string min = Mathf.Floor ((compteurmax - compteur) / 60).ToString ("00");
		string sec = Mathf.Floor ((compteurmax - compteur) % 60).ToString ("00");

		GUI.Label (MyRect (500, 0, 100, 20), "Point : " + nbEnnemiTue.ToString());
		GUI.Label (MyRect (500, 21, 300, 20), "Temps restant : " + min+":"+sec);
		GUI.Label (MyRect (500, 42, 300, 20), "Vie restante : " + nbvie.ToString());
		GUI.Label (MyRect (500, 63, 200, 20), "Nombre de crédits : " + compteurpoints.ToString());

		if (GUI.Button (MyRect (100, 10, 150, 50), "Pause")){
			Time.timeScale =0;
			state=STATES.PAUSE;
		}
		if (GUI.Button (MyRect (260, 10, 150, 50), "Selection arme")){
			Time.timeScale =0;
			if (niveau==1){
				placementTourelle1.SetActive(true);
			}
			if (niveau==2){
				placementTourelle2.SetActive(true);
			}
			state=STATES.SELECTIONARME;			
		}

		if (GUI.RepeatButton(MyRect (0, 0, 50, 480), textureBouton[1])){
			if (niveau==1){
				cam1.transform.RotateAround(cam1.transform.parent.position, new Vector3(0,1,0),50*Time.deltaTime);
				cam1.transform.LookAt (cam1.transform.parent);
			}
			else {
				cam2.transform.RotateAround(cam2.transform.parent.position, new Vector3(0,1,0),50*Time.deltaTime);
				cam2.transform.LookAt (cam2.transform.parent);
			}
		}
		if (GUI.RepeatButton(MyRect (750, 0, 50,480), textureBouton[0])){
			if (niveau==1){
				cam1.transform.RotateAround(cam1.transform.parent.position, new Vector3(0,-1,0),50*Time.deltaTime);
				cam1.transform.LookAt (cam1.transform.parent);
			}
			else {
				cam2.transform.RotateAround(cam2.transform.parent.position, new Vector3(0,-1,0),50*Time.deltaTime);
				cam2.transform.LookAt (cam2.transform.parent);
			}
		}
	}

	void OnGUIselectionarme (){
		GUI.Label (MyRect (300, 0, 200, 20), "Nombre de crédits : " + compteurpoints.ToString());

		if (GUI.Button (MyRect (100, 10, 150, 50), "Retour au jeu")){
			Time.timeScale =1;
			if (niveau==1){
				placementTourelle1.SetActive(false);
			}
			if (niveau==2){
				placementTourelle2.SetActive(false);
			}
			state=STATES.JEU;
		}
		if (GUI.Button (MyRect (470, 10, 100, 100), textureBoutonTourelle[0])){
			choixarme=0;
		}
		if (GUI.Button (MyRect (580, 10, 100, 100), textureBoutonTourelle[1])){
			choixarme=1;
		}
		if (GUI.Button (MyRect (690, 10, 100, 100), textureBoutonTourelle[2])){
			choixarme=2;
		}
	}	

	void Update (){
		switch (state){
			case STATES.INITIALISATION:
				updateinitialisation ();
				break;
			case STATES.SELECTIONARME:
				updatearme ();
				break;
			case STATES.JEU:
				updatejeu ();
				break;
		}
	}

	void updateinitialisation (){
		nbvie = 50;
		compteur = 0.0f;
		compteurpoints = 50;
		mainCam.SetActive(false);
		if (niveau==1){
			niveau1.SetActive(true);
			cam1.transform.LookAt (cam1.transform.parent);
		}
		else{
			niveau2.SetActive(true);
			cam2.transform.LookAt (cam2.transform.parent);
		}		
		nbRespawn = 1;
		compteurTemps = 0;
		StartCoroutine("ajoutPoint");
		StartCoroutine("CreationEnnemi");
		state = STATES.JEU;
	}

	void updatearme(){
		RaycastHit hit;
		Collider collider;
		Ray ray;
		
		if (Input.GetMouseButtonUp (0)){
			ray = Camera.main.ScreenPointToRay (Input.mousePosition);
			if (Physics.Raycast (ray, out hit, 10000)){
				collider = hit.collider;
				if (collider.name == "Place" || collider.name == "Place(Clone)" ){
					if (compteurpoints>pointNecessaire[choixarme]){
						compteurpoints=compteurpoints-pointNecessaire[choixarme];
						GameObject arme= GameObject.Instantiate(tour[choixarme],collider.transform.position,Quaternion.identity) as GameObject;
						arme.transform.parent = GameObject.Find("Tourelles").transform;
						arme.transform.rotation=collider.gameObject.transform.rotation;
						Destroy(collider.gameObject);
					}
				}
			}
		}
	}

	void updatejeu (){
		if (nbvie <= 0){
			if (niveau==1){
				niveau1.SetActive(false);
			}
			else{
				niveau2.SetActive(false);
			}
			alldestruction();
			StopCoroutine("ajoutPoint");
			StopCoroutine("CreationEnnemi");
			destructionRespawn();
			niveau=1;
			mainCam.SetActive(true);
			state=STATES.DEFAITE;
		}

		compteur += Time.deltaTime;
		if (compteur >= compteurmax) {
			if (niveau==1){
				niveau1.SetActive(false);
			}
			else{
				niveau2.SetActive(false);
			}
			alldestruction ();
			StopCoroutine("ajoutPoint");
			StopCoroutine("CreationEnnemi");
			destructionRespawn();
			mainCam.SetActive(true);
			state = STATES.VICTOIRE;
		}
		ennemi = GameObject.FindGameObjectsWithTag ("Ennemi");
	}

	IEnumerator ajoutPoint(){
		while (true){
			yield return new WaitForSeconds (2);
			compteurpoints++;
		}
	}

	IEnumerator CreationEnnemi(){
		while (true){
			if (niveau == 1){		
				for(int i=0; i<respawn1.Length; i++){
					respawn1[i].SetActive(false);
				}
				for(int i=0; i<nbRespawn; i++){
					respawn1[Random.Range(0,respawn1.Length)].SetActive(true);
				}
				if (nbRespawn<respawn1.Length){
					compteurTemps++;
					if (compteurTemps == 25 ){
						compteurTemps = 0;
						nbRespawn++;
					}
				}
			}
			if (niveau == 2){
				for(int i=0; i<respawn2.Length; i++){
					respawn2[i].SetActive(false);
				}
				for(int i=0; i<nbRespawn; i++){
					respawn2[Random.Range(0,respawn2.Length)].SetActive(true);
				}
				if (nbRespawn<respawn2.Length){
					compteurTemps++;
					if (compteurTemps == 20 ){
						compteurTemps=0;
						nbRespawn++;
					}
				}
			}
			yield return new WaitForSeconds (1);
		}
	}

	void destructionRespawn (){
		if (niveau == 1){
			for (int i= 0; i<respawn1.Length;i++){
				respawn1[i].SetActive(false);
			}
		}
		if (niveau == 2){
			for (int i= 0; i<respawn2.Length;i++){
				respawn2[i].SetActive(false);
			}
		}
	}

	void alldestruction (){
		GameObject allTour= GameObject.Find("Tourelles");
		foreach(Transform tour in allTour.transform){
			GameObject place = Instantiate(PlaceArme,tour.position,Quaternion.identity) as GameObject;		
			if (niveau==1){
				place.transform.parent = placementTourelle1.transform ;
			}
			if (niveau==2){
				place.transform.parent = placementTourelle2.transform ;
			}
			place.transform.rotation=tour.transform.rotation;
		}

		GameObject [] dest = GameObject.FindGameObjectsWithTag ("Destruction");
		foreach (GameObject destruction in dest){
			Destroy (destruction);
		}

		GameObject [] dest2 = GameObject.FindGameObjectsWithTag ("Ennemi");
		foreach (GameObject destruction2 in dest2){
			Destroy (destruction2);
		}
	}

	static public Rect MyRect(float x, float y, float size_x, float size_y){
		return new Rect (x * Screen.width / 800, y * Screen.height / 480, size_x * Screen.width / 800 , size_y * Screen.height / 480);
	}
}