using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using Photon.Pun;

public class RacerLobbyUI : MonoBehaviour {

	public int lastPlayerCount = 0;

	public float startWaitTime = 59f, extraPlayers = 30f, countdownLength = 5f;

	public TMP_Text waitForPlayersTimer, waitForPlayersText, startMatchText, countdownTimer, racerCount;

	public GameLauncher launcher;
	public TrackManagerScript manager;

	public bool cancelCountdown, countingDown, thirtySecondsPassed = false, fullGame = false;
	public LobbyCanvasHandler handler;
	//public GameGenerator gameGenerator;

	//public GameObject StaticLoadingScreen;

	float loadingTime;
	float timeToWaitForLoading = 1f;


	public bool wasHost;

	void Start() {
		loadingTime = Time.unscaledTime;
		wasHost = PhotonNetwork.IsMasterClient;
		StartCoroutine (DotDotDot ());
	}

	void Update() {
		if (!manager) {
			manager = FindObjectOfType<TrackManagerScript> ();
		}

		if(PhotonNetwork.IsMasterClient && countingDown && !wasHost) {
			//Debug.LogError ("Change Master");
			PhotonGameDebugger.IncrementNumberOfMessages("match start time");
			// send out the random seed again 
			//gameGenerator.SendRandomSeed(GameGenerator.GetOldRandomSeed());
			Host (false);
			wasHost = true;
		}

		if (PhotonNetwork.InRoom && !PhotonNetwork.IsMasterClient) {
			countingDown = true;
		}


		if (PhotonNetwork.IsMasterClient && launcher.totalPlayers <= 1 && waitForPlayersTimer.gameObject.activeInHierarchy) {
			//Debug.LogError ("Hide Player Timer");
			countingDown = false;
			Cancel();
			waitForPlayersTimer.gameObject.SetActive(false);


		} else if (PhotonNetwork.IsMasterClient && !countingDown) {
			if(launcher.totalPlayers > 1) {
				//Debug.LogError ("Host Match");
				countingDown = true;
				lastPlayerCount = launcher.totalPlayers;
				Host (true);
			}


		} else if (PhotonNetwork.IsMasterClient && countingDown) {
			if (lastPlayerCount < launcher.totalPlayers) {
				//Debug.LogError ("Restart Countdown");
				lastPlayerCount = launcher.totalPlayers;
				Host (false);
			} else if (lastPlayerCount > launcher.totalPlayers) {
				lastPlayerCount = launcher.totalPlayers;
			}
		}

		if (PhotonNetwork.InRoom) {
			if (launcher.totalPlayers == 8 && !fullGame) {
				cancelCountdown = true;
				fullGame = true;
				StartCoroutine (BeginMatchCountdown ());
			}
			wasHost = PhotonNetwork.IsMasterClient;
			racerCount.SetText ("Racers " + launcher.totalPlayers + "/" + launcher.maxPlayersPerRoom);
		}

		if (Input.GetKeyDown (KeyCode.P)) {
			Host (false);
		}

		//if (StaticLoadingScreen.activeInHierarchy && Time.unscaledTime > loadingTime) {
		//	StaticLoadingScreen.SetActive(false);
		//}
	}

	public void Host(bool initialStart) {
		PhotonGameDebugger.IncrementNumberOfMessages("match start time");
		float sendTime = (float)PhotonNetwork.Time;
		if (initialStart) {
			//Debug.LogError ("Initial Start Hit");
			thirtySecondsPassed = false;
			cancelCountdown = false;
			launcher.photonView.RPC ("SetMatchStartTime", RpcTarget.AllBuffered, sendTime, sendTime + startWaitTime, false);
		} else if (thirtySecondsPassed) {
			//Debug.LogError ("hit the time jump");
			launcher.photonView.RPC ("SetMatchStartTime", RpcTarget.AllBuffered, sendTime, sendTime + extraPlayers, true);
		}
	}

	IEnumerator DotDotDot () {
		while (!PhotonNetwork.InRoom) {
			yield return null;
		}
		while (launcher.totalPlayers < 8) {
			waitForPlayersText.SetText ("[ Waiting for more players    ]");
			yield return new WaitForSeconds (0.5f);
			waitForPlayersText.SetText ("[ Waiting for more players.   ]");
			yield return new WaitForSeconds (0.5f);
			waitForPlayersText.SetText ("[ Waiting for more players..  ]");
			yield return new WaitForSeconds (0.5f);
			waitForPlayersText.SetText ("[ Waiting for more players... ]");
			yield return new WaitForSeconds (0.5f);
		}
	}

	public void Cancel() {
		cancelCountdown = true;
		launcher.ResetMatchStartTime();
	}

	public IEnumerator CountdownToStart() {
		
		// Allow for late joiners to catch up
		while ((float)PhotonNetwork.Time > launcher.GetMatchStartTime ()) {
			yield return null;
		}

		waitForPlayersTimer.gameObject.SetActive(true);
		//Debug.LogError ("Cancel Countdown: " + cancelCountdown + ", GMST: " + launcher.GetMatchStartTime ().ToString () + ", PNT: " + PhotonNetwork.Time.ToString ());
		while (!cancelCountdown && launcher.GetMatchStartTime() > -1 && (float)PhotonNetwork.Time < launcher.GetMatchStartTime()) {
			if ((launcher.GetMatchStartTime () - (float)PhotonNetwork.Time) <= 30f) {
				thirtySecondsPassed = true;
			}
			waitForPlayersTimer.SetText("0:" + (launcher.GetMatchStartTime() - (float)PhotonNetwork.Time).ToString("00"));
			yield return null;
		}

		if (cancelCountdown) {
			//Debug.LogError ("Actually Canceled");
			cancelCountdown = false;
			yield break;
		}
		waitForPlayersTimer.gameObject.SetActive(false);
		waitForPlayersText.gameObject.SetActive(false);
		startMatchText.gameObject.SetActive(true);

		launcher.BeginMatch ((float)PhotonNetwork.Time + countdownLength);
	}

	public IEnumerator BeginMatchCountdown() {
		Debug.LogError("Here!");
		PhotonNetwork.CurrentRoom.IsOpen = false;
		PhotonNetwork.CurrentRoom.IsVisible = false;
		countdownTimer.gameObject.SetActive(true);

		if (!fullGame) {
			//Debug.LogError ("It ran once?");
			while (!cancelCountdown && launcher.GetMatchStartTime () > -1 && (float)PhotonNetwork.Time < launcher.GetMatchStartTime ()) {
				countdownTimer.SetText ((launcher.GetMatchStartTime () - (float)PhotonNetwork.Time).ToString ("F0"));
				yield return null;
			}
		}

		countdownTimer.gameObject.SetActive(false);

		//StaticLoadingScreen.SetActive(true);
		loadingTime = Time.unscaledTime + timeToWaitForLoading;
		handler.SetInLobbyCanvasActive();
		launcher.StartMatch();
	}
}

