using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Photon.Pun;
public class CanvasManagerScript :  MonoBehaviourPunCallbacks{

	public GameObject startJoin, lobby, raceCountDown, timeDisplay, customizeSettings;
	public GameObject quit, backToLobby, exitGame, pauseRace;
	public bool editMode = false;

	public TrackManagerScript manager;

    // Start is called before the first frame update
    void Start () {
		if (!manager) {
			manager = FindObjectOfType<TrackManagerScript> ();
		}
    }

    // Update is called once per frame
    void Update () {

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

		if (PhotonNetwork.IsConnected && Time.timeScale != 1f) {
			Time.timeScale = 1f;
		}

		if (SceneManager.GetActiveScene ().name == "RKR-Lobby") {
			if (PhotonNetwork.IsConnected) {
				backToLobby.SetActive (true);
			} else {
				backToLobby.SetActive (false);
			}
		}

		#if UNITY_EDITOR
		if(editMode){
			backToLobby.SetActive(true);
			exitGame.SetActive(true);
			pauseRace.SetActive(false);
		} else {
			backToLobby.SetActive(false);
			exitGame.SetActive(false);
			pauseRace.SetActive(true);
		}
		#endif

		if (Input.GetKeyDown (KeyCode.Escape) && quit != null) {

			if (!quit.activeInHierarchy) {
				quit.SetActive (true);
				if (!PhotonNetwork.IsConnected) {
					Time.timeScale = 0f;
				}
			} else {
				quit.SetActive (false);
				if (!PhotonNetwork.IsConnected) {
					Time.timeScale = 1f;
				}
			}
		}
    }

	public void RaceSelect () {
		if (manager) {
			manager.guiActive = true;
			startJoin.SetActive (false);
		}
	}

	public void ReturnToLobby () {
		StartCoroutine(TotalDisconnect());
	}

	public void ExitGame () {
		Application.Quit ();
	}

	IEnumerator TotalDisconnect() {

		if (PhotonNetwork.IsConnected) {
			
			if (PhotonNetwork.InRoom) {
				PhotonNetwork.LeaveRoom();
			}

			PhotonNetwork.Disconnect ();

			while (PhotonNetwork.IsConnected) {
				//Debug.Log ("waiting");
				yield return null;
			}
		}

		SceneManager.LoadScene ("RKR-Lobby");
	}
}