using UnityEngine;
using System.Collections;

public class s_Controller : MonoBehaviour
{
	public Texture2D flyTexture;
	public Texture2D outlineTexture;
	public GameObject starTextures;
	public GameObject dimTexture;
	public GameObject psGetStar;
	public Camera forgroundCamera;
	public GUIStyle testStyle; //Draw with a bigger font
	public GameObject backgroundMusic;
	public GameObject ButtonNextLevel;
	
	public TextMesh UIFly;
	public TextMesh UIDoubleJump;
	public TextMesh UIRepair;
	public TextMesh UITongue;
	
	
	GameObject player; //Gets the player
	s_Player playerScript; //Gets player script to check if you won/lost
	
	public bool won = false; //Draw win stuff if you won
	public float startTime;
	bool mLoading = false;
	bool wonNextButton = false;
	bool lose = false; //Draw lose stuff if you lose
	float timer;
	int timerMax = 999;
	int scoreTextSize = 35;
	int caughtFlies;
	int totalFlies; //For drawing the flies/outlines
	
	int prevDoubleJumpCount;
	int prevRepairCount;
	int prevTongueCount;
	Vector3 uiFirstPos;
	float uiYOffset = 0.7f;
	string UIBulgeAnimName = "UIBulge";
	
	float timeBetweenStars = 0.75f;
	float starOffset = 1.75f;
	
	//int flyOffset = 25; //For drawing spaces inbetween fly/outlines
	//bool showWindow = false; //opens and closes pause menu
	
	void Start()
	{	
		startTime = Time.time; //This will be updated on first jump!!
		
		//This is so I can check later if the script is on or off (win lose)
		player = GameObject.Find("Player");
		playerScript = player.GetComponent<s_Player>();
		
		//Gets the total flies
		GameObject[] flies = GameObject.FindGameObjectsWithTag("Fly");
		totalFlies = flies.Length;
		caughtFlies = 0;
	
		InitUI();
		
		if (!AudioManager.mute)
			backgroundMusic.audio.Play();
	}
	
	void InitUI()
	{
		UpdateUIFly(0);
		UIFly.transform.parent.animation["UIBulge"].time = 1;
		UpdateUIPowerups();
		
		float currentOffset = uiYOffset;
		uiFirstPos = UIDoubleJump.transform.parent.transform.position;
		
		if (GameObject.Find("DoubleJump"))
		{
			prevDoubleJumpCount = playerScript.doubleJumpCount;
			UIDoubleJump.GetComponent<TextMesh>().text = "X" + prevDoubleJumpCount;
			
			uiFirstPos.z -= uiYOffset;
		}
		else
			Destroy(UIDoubleJump.transform.parent.gameObject);
		
		if (GameObject.Find("Repair"))
		{
			prevRepairCount = playerScript.repairCount;
			UIRepair.GetComponent<TextMesh>().text = "X" + prevRepairCount;
			
			UIRepair.transform.parent.transform.position = uiFirstPos;
			uiFirstPos.z -= uiYOffset;
		}
		else
			Destroy(UIRepair.transform.parent.gameObject);
		
		if (GameObject.Find("PickupTongue"))
		{
			prevTongueCount = playerScript.tongueCount;
			UIFly.transform.parent.animation[UIBulgeAnimName].time = 1;
			UITongue.GetComponent<TextMesh>().text = "X" + prevTongueCount;
			
			UITongue.transform.parent.transform.position = uiFirstPos;
		}
		else
			Destroy(UITongue.transform.parent.gameObject);
	}
	
	void Update()
	{	
		//Update timer
		if (!won && !lose)
			timer = Time.time - startTime;
		
#if UNITY_EDITOR
		//Reset game on R
		if (Input.GetKeyDown(KeyCode.R))
		{
			for (int i = 0; i < Application.levelCount - s_LevelSelect.levelOffset; ++i)
				PlayerPrefs.SetInt("Stars " + i, 0);
			
			Debug.Log("Game data has been reset!");
		}
#endif
		
		
		//Gets input: click for osx, windows, and editor. Touch for android and iphone
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_WEBPLAYER
		if (Input.GetMouseButtonDown(0))
#endif
					
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
		for (int i = 0; i < Input.touchCount; ++i)
            if (Input.GetTouch(i).phase.Equals(TouchPhase.Began))
#endif
						
		{
				
			//Then makes a ray, for touch or click position
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
 			Ray ray = forgroundCamera.ScreenPointToRay(Input.GetTouch(i).position);
#endif
				
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_WEBPLAYER
			Ray ray = forgroundCamera.ScreenPointToRay(Input.mousePosition);
#endif
			
			if (mLoading)
				return;
				
			RaycastHit hit;
				
			//If you click on something
	  		if (Physics.Raycast(ray, out hit, 200.0f))
			{
			
				if (hit.collider.gameObject.name == "ButtonLevelMainMenu")
				{
					s_Buttons button = hit.collider.gameObject.GetComponent<s_Buttons>();
					button.Clicked();
					
					mLoading = true;
					StartCoroutine(MainMenu());
				}
				else if (hit.collider.gameObject.name == "ButtonLevelRestart")
				{
					s_Buttons button = hit.collider.gameObject.GetComponent<s_Buttons>();
					button.Clicked();
						
					mLoading = true;
					StartCoroutine(RestartLevel());
				}
				else if (hit.collider.gameObject.name == "ButtonLevelNextLevel")
				{
					s_Buttons button = hit.collider.gameObject.GetComponent<s_Buttons>();
					button.Clicked();
						
					mLoading = true;
					StartCoroutine(NextLevel());
				}
					
			}	
		}
		
		if (!won && playerScript.enabled == false)
		{
			won = true;
			//Create win screen
			Instantiate(dimTexture, dimTexture.transform.position, dimTexture.transform.rotation);
			Instantiate(starTextures, starTextures.transform.position, starTextures.transform.rotation);
			AudioManager.PlaySound(AudioManager.win);
			
			timer = Mathf.Round(timer * 100) / 100;
			
			StartCoroutine(UpdateScore());
		}
		
		//Make sure you don't lose if you already won
		if (!lose && playerScript.lost && !won)
		{
			lose = true;
			Instantiate(dimTexture, dimTexture.transform.position, dimTexture.transform.rotation);
			AudioManager.PlaySound(AudioManager.lose);
		}
	}
	
	public void UpdateUIPowerups()
	{
		//This allows them to be null, because early on they don't all show up
		
		if (UIDoubleJump != null && playerScript.doubleJumpCount != prevDoubleJumpCount)
		{
			UIDoubleJump.GetComponent<TextMesh>().text = "X" + playerScript.doubleJumpCount.ToString();
			prevDoubleJumpCount = playerScript.doubleJumpCount;
			UIDoubleJump.transform.parent.animation.Play(UIBulgeAnimName);
		}
		if (UIRepair != null && playerScript.repairCount != prevRepairCount)
		{
			prevRepairCount = playerScript.repairCount;
			UIRepair.transform.parent.animation.Play(UIBulgeAnimName);
			UIRepair.GetComponent<TextMesh>().text = "X" + playerScript.repairCount.ToString();
		}
		if (UITongue != null && playerScript.tongueCount != prevTongueCount)
		{
			prevTongueCount = playerScript.tongueCount;
			UITongue.transform.parent.animation.Play(UIBulgeAnimName);
			UITongue.GetComponent<TextMesh>().text = "X" + playerScript.tongueCount.ToString();
		}
	}
	
	public void UpdateUIFly(int aAmount)
	{
		caughtFlies += aAmount;
		
		UIFly.transform.parent.animation.Play(UIBulgeAnimName);
		UIFly.GetComponent<TextMesh>().text = caughtFlies + "/" + totalFlies;
	}
	
	IEnumerator UpdateScore()
	{
		//If you have a new high score, or there was no score, update it
		int currLevel = Application.loadedLevel - s_LevelSelect.levelOffset;
		s_Score scoreScript = GameObject.Find("Score").GetComponent<s_Score>();
		int currStars = PlayerPrefs.GetInt("Stars " + currLevel);
			
		//Set how many stars you get
		if (timer <= scoreScript.star3)
		{
			if (currStars < 3 || currStars == s_LevelSelect.invalidLevel)
				PlayerPrefs.SetInt("Stars " + currLevel, 3);
		}
		else if (timer <= scoreScript.star2)
		{
			if (currStars < 2 || currStars == s_LevelSelect.invalidLevel)
				PlayerPrefs.SetInt("Stars " + currLevel, 2);
		}
		else if (timer <= scoreScript.star1)
		{
			if (currStars < 1 || currStars == s_LevelSelect.invalidLevel)
				PlayerPrefs.SetInt("Stars " + currLevel, 1);
		}
		else
		{
			if (currStars == s_LevelSelect.invalidLevel)
				PlayerPrefs.SetInt("Stars " + currLevel, 0);
		}
		
		//Then wait a bit for dramatic stars
		yield return new WaitForSeconds(0.5f);
		
		//Then play the animations
		if (timer <= scoreScript.star1)
		{	
			GameObject star = GameObject.Find("1Star");
			star.animation.Play("Star1");
			
			yield return new WaitForSeconds(star.animation.clip.length + 0.05f);
			
			Vector3 pos = forgroundCamera.ViewportToWorldPoint(star.transform.localPosition);
			pos.x -= starOffset;
			pos.y = psGetStar.transform.position.y; //this is so it isn't behind the camera
			Instantiate(psGetStar, pos, psGetStar.transform.rotation);
			AudioManager.PlaySound(AudioManager.getStar1);
			
			yield return new WaitForSeconds(timeBetweenStars += 0.75f);
		}
		if (timer <= scoreScript.star2)
		{
			GameObject star = GameObject.Find("2Star");
			star.animation.Play("Star2");	
			
			yield return new WaitForSeconds(star.animation.clip.length + 0.05f);
			
			Vector3 pos = forgroundCamera.ScreenToWorldPoint(star.guiTexture.GetScreenRect().center);
			pos.y = psGetStar.transform.position.y; //this is so it isn't behind the camera
			Instantiate(psGetStar, pos, psGetStar.transform.rotation);
			AudioManager.PlaySound(AudioManager.getStar2);
			
			yield return new WaitForSeconds(timeBetweenStars += 0.75f);
		}
		if (timer <= scoreScript.star3)
		{
			GameObject star = GameObject.Find("3Star");
			star.animation.Play("Star3");
			
			yield return new WaitForSeconds(star.animation.clip.length + 0.05f);
			
			Vector3 pos = forgroundCamera.ScreenToWorldPoint(star.guiTexture.GetScreenRect().center);
			pos.x += starOffset;
			pos.y = psGetStar.transform.position.y; //this is so it isn't behind the camera
			Instantiate(psGetStar, pos, psGetStar.transform.rotation);
			AudioManager.PlaySound(AudioManager.getStar3);
			
			yield return new WaitForSeconds(0.75f);
		}
		
		//bring up the next button
		ButtonNextLevel.renderer.enabled = true;
		ButtonNextLevel.collider.enabled = true;
		
	}
	
	IEnumerator NextLevel()
	{	
		//AudioManager.PlaySound(AudioManager.buttonYes);
		
		yield return new WaitForSeconds(AudioManager.buttonYes.length);
		
		if (Application.loadedLevel == Application.levelCount - 1)
			Application.LoadLevel("MainMenu");
		else
			Application.LoadLevel(Application.loadedLevel + 1);
	}
	
	IEnumerator RestartLevel()
	{
		//AudioManager.PlaySound(AudioManager.buttonYes);
		
		yield return new WaitForSeconds(AudioManager.buttonYes.length);
		
		Application.LoadLevel(Application.loadedLevelName);
	}
	
	IEnumerator MainMenu()
	{
		//AudioManager.PlaySound(AudioManager.buttonYes);
		
		yield return new WaitForSeconds(AudioManager.buttonNo.length);
		
		Application.LoadLevel("MainMenu");
	}
	
	IEnumerator QuitGame()
	{
		AudioManager.PlaySound(AudioManager.buttonNo);
		
		yield return new WaitForSeconds(AudioManager.buttonYes.length);
		
		Application.Quit();
	}
	
	IEnumerator Timer()
	{
		yield return new WaitForSeconds(1.0f);
		
		if (won || lose)
			yield break;
		
		timer += 1;
		Debug.Log(timer);
		
		if (timer != timerMax)
			StartCoroutine(Timer());
	}
	
	void OnGUI()
	{	
		
		//GUI.Label(new Rect(Screen.width / 2 - 300, 5, 600, 200), (Mathf.Round(timer * 100) / 100).ToString(), testStyle);
		
		//WON
		if (won)
		{
			//You Win message
			GUI.Label(new Rect(Screen.width / 2 - 300, 5, 600, 200), "Level Complete!", testStyle);
			
			//Time
			int orgSize = testStyle.fontSize;
			testStyle.fontSize = scoreTextSize;
			
			GUI.Label(new Rect(Screen.width / 2 - 125, 75, 250, 200), "Score: " + timer + " sec", testStyle);
			
			testStyle.fontSize = orgSize;
			
			//Next Level Button
			if (wonNextButton)
				if (GUI.Button(new Rect(Screen.width / 2 - 50, Screen.height / 2 + 75, 100, 50), "Next Level"))
				{	
					StartCoroutine(NextLevel());
				}
		}
		
		//LOSE
		if (lose)
		{
			//You Lose message
			GUI.Label(new Rect(Screen.width / 2 - 125, 5, 300, 200), "Oh no!", testStyle);
		}
		
		
		/*
		//Draws the flies, or outlines
		GameObject[] flies = GameObject.FindGameObjectsWithTag("Fly");
		
		for (int i = 0; i < totalFlies; ++i)
		{
			if (i < (totalFlies - flies.Length))
				GUI.DrawTexture(new Rect(flyOffset * i + 10, 40, 25, 25), flyTexture);	
			else	
				GUI.DrawTexture(new Rect(flyOffset * i + 10, 40, 25, 25), outlineTexture);
		}
		*/
		
		//Level
		/*
		int level = Application.loadedLevel - s_LevelSelect.levelOffset;
		GUI.Label(new Rect(10, 5, 200, 200), "Level: " + level.ToString());
		*/
		
		
		//Pause Button
		/*
		if (GUI.Button(new Rect(10, Screen.height - 50, 60, 40), "Pause"))
		{
			playerScript.paused = true;
			showWindow = true;
		}
		
		if(showWindow)
		{
			//GUILayout.Window(0,new Rect(Screen.width,Screen.height,500,500), DoMyWindow, "Pause", GUILayout.Width(100));
			GUILayout.Window(0,new Rect(0, 0, Screen.width, Screen.height), DoMyWindow, "Pause", GUILayout.Width(100));
		}
		
		//Restart Button
		if (GUI.Button(new Rect(Screen.width - 80, 5, 70, 70), "Restart"))
		{	
			StartCoroutine(RestartLevel());
		}
		
		//Main Menu Button
		if (GUI.Button(new Rect(Screen.width - 80, 85, 70, 70), "Main Menu"))
			StartCoroutine(MainMenu());
		*/
	}
	/*
	//pause menu buttons
	void DoMyWindow(int windowID)
	{
		if(GUILayout.Button ("Main Menu"))
		{
			Application.LoadLevel ("MainMenu");
		}
		
		if(GUILayout.Button ("Restart"))
		{
			Application.LoadLevel (Application.loadedLevel);
			
		}
		
		if(GUILayout.Button ("How to Play"))
		{
			Application.LoadLevel ("HowToPlay");
			
		}
		
		if(GUILayout.Button ("Quit"))
		{
			Application.Quit ();
		}
		
		if(GUILayout.Button ("Back to Game"))
		{
			playerScript.paused = false;
			showWindow = false;
		}
	}
	*/
	
}