using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using System.Linq;
using System.IO;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;


public class TrackManagerScript : MonoBehaviourPunCallbacks {

	[ReadOnly]
	public GameObject playerDefaults;
	[ReadOnly]
	public Transform trackStart, racerSpots;
	[ReadOnly]
	public int totalLaps = 3;
	[ReadOnly]
	public Texture sampleFile;

	[ReadOnly]
	public static List<string> trackNames;
	[ReadOnly]
	public bool loadSceneCalled = false, guiActive = false;
	[ReadOnly]
	public Vector2 scrollSpot;
	[ReadOnly]
	public GUISkin sampleSkin;
	[ReadOnly]
	public GUIContent[] playableTracks;
	[ReadOnly]
	public Vote leadingVote;
	[ReadOnly]
	public Vote[] trackVotes;
	[ReadOnly]
	public int selectGridInt = 0, gridSpots = 4;
	[ReadOnly]
	public string selectedLevel = "";

	[ReadOnly]
	public CanvasManagerScript canvasManager;

	void Start () {
		if (!trackStart) {
			trackStart = GameObject.FindGameObjectWithTag ("StartFinish").transform;
		}
		if (!racerSpots) {
			racerSpots = GameObject.Find ("Racer Spots").transform;
		}
		if (!sampleFile) {
			sampleFile = Resources.Load<Texture> ("Button Images/RKR Icon");
		}
		if (!sampleSkin) {
			sampleSkin = Resources.Load<GUISkin> ("Button Images/TrackSelectSkin");
		}
		if (!canvasManager)
		{
			canvasManager = GetComponentInChildren<CanvasManagerScript>();
		}
		selectGridInt = -1;

		GetTrackScenes ();

		Vector3 adjustedPos = new Vector3 (trackStart.position.x, trackStart.position.y + 1.13f, trackStart.position.z - 2f);
		if (racerSpots && SceneManager.GetActiveScene().name != "RKR - Esports Lobby" && SceneManager.GetActiveScene().name != "Esports-Lobby") {
			if (PhotonNetwork.IsConnected) {
				bool joinAsSpectator = false;
				object prop;
				if (PhotonNetwork.LocalPlayer.CustomProperties.TryGetValue("IsSpectator", out prop))
				{
					joinAsSpectator = (bool)prop;
					canvasManager.RaceOrSpectateCanvas(joinAsSpectator);
					if (joinAsSpectator)
					{
						Debug.Log(PhotonNetwork.LocalPlayer.ActorNumber - 1 + " - Player is Specator");

						SpectatorController spectatorController = FindObjectOfType<SpectatorController>();
						spectatorController.SpectateAnyPlayer();
					}
					else
					{
						
						//Debug.Log(PhotonNetwork.LocalPlayer.ActorNumber - 1);
						GameObject newPlayer = PhotonNetwork.Instantiate("Base Racer", racerSpots.GetChild(PhotonNetwork.LocalPlayer.ActorNumber - 1).position, trackStart.rotation);
					}
				}

			} else {
				GameObject.Instantiate (playerDefaults, racerSpots.GetChild (0).position, trackStart.rotation);
			}
		}

		/*
		if (SceneManager.GetActiveScene ().name != "PhotonTesting 1" && SceneManager.GetActiveScene ().name != "RKR-Lobby" && SceneManager.GetActiveScene().name != "Esports-Lobby") {
			guiActive = false;
		} else { 
			guiActive = true;
		}
		*/
	}

	public void GetTrackScenes () {

		trackNames = new List<string> ();
		for (int i = 2; i < SceneManager.sceneCountInBuildSettings; i++) {
			trackNames.Add (SceneUtility.GetScenePathByBuildIndex (i).Replace ("Assets/Racetrack Scenes/", "").Replace ("Demo Tracks/", "").Replace (".unity", ""));
		}

		if (trackNames.Count < 1) {
			return;
		}

		playableTracks = new GUIContent[trackNames.Count];
		trackVotes = new Vote[trackNames.Count];

		for (int t = 0; t < trackNames.Count; t++) {
			trackVotes [t] = new Vote (trackNames [t], 0);
			playableTracks [t] = new GUIContent (trackNames [t], sampleFile);
		}
		leadingVote = trackVotes [0];
		selectedLevel = trackVotes [0].name;
	}

	public static bool FindTracks () {
		Debug.Log ("Scene Count Build Settings: " + SceneManager.sceneCountInBuildSettings);
		for (int i = 2; i < SceneManager.sceneCountInBuildSettings; i++) {
			Debug.LogError (SceneUtility.GetScenePathByBuildIndex (i).Replace ("Assets/Racetrack Scenes/", "").Replace (".unity", ""));
		}
		return true;
		/*
		string[] tempNames = Directory.GetFiles (Application.dataPath + "/Racetrack Scenes");
		trackNames = new List<string> ();

		if (tempNames.Length < 1) {
			Debug.Log ("None");
			return false;
		}
		foreach (string track in tempNames) {
			if (!track.Contains (".meta")) {
				#if UNITY_EDITOR_WIN
				string trackName = track.Substring(track.LastIndexOf('\\') + 1);
				#else
				string trackName = track.Substring(track.LastIndexOf('/') + 1);
				#endif
				trackNames.Add (trackName.Replace (".unity", ""));
			}
		}

		return true;
		*/
	}

	// Update is called once per frame
	void OnGUI () {
		if (!guiActive) {
			return;
		}

		Rect innerBorder = new Rect (Screen.width / 16f, Screen.height / 16f, Screen.width * (7f / 8f), Screen.height * (7f / 8f));
		Rect outerBorder = new Rect (Screen.width / 32f, Screen.height / 32f, Screen.width * (15f / 16f), Screen.height * (15f / 16f));
		
		GUILayout.BeginArea (outerBorder);

		scrollSpot = GUILayout.BeginScrollView (scrollSpot);

		GUILayout.BeginHorizontal ();
		GUILayout.FlexibleSpace ();
		GUILayout.BeginVertical ();
		GUILayout.FlexibleSpace ();

		if (selectGridInt == -1) {
			selectGridInt = GUILayout.SelectionGrid (selectGridInt, playableTracks, gridSpots, sampleSkin.button, GUILayout.MaxWidth(innerBorder.width));
		} else {
			GUILayout.SelectionGrid (selectGridInt, playableTracks, gridSpots, sampleSkin.customStyles[3], GUILayout.MaxWidth(innerBorder.width));
			if (PhotonNetwork.IsConnected) {
				photonView.RPC ("CastVote", RpcTarget.AllBuffered, selectGridInt);
			} else {
				SceneManager.LoadScene (trackNames [selectGridInt]);
			}
			guiActive = false;
		}

		GUILayout.FlexibleSpace ();
		GUILayout.EndVertical ();
		GUILayout.FlexibleSpace ();
		GUILayout.EndHorizontal ();


		GUILayout.EndScrollView ();
		GUILayout.EndArea ();
	}

	IEnumerator LoadRacetrack (int trackNum) {
		if (loadSceneCalled) {
			yield break;
		}
		loadSceneCalled = true;
		yield return new WaitForSecondsRealtime (2f);
		SceneManager.LoadScene (trackNames [trackNum]);
	}

	public void Update () {
		if (Input.GetKeyDown (KeyCode.Semicolon)) {
			bool test = FindTracks ();
			Debug.Log ("End");
			return;
			/*
			if (test) {
				SceneManager.LoadScene (trackNames [1]);
			}
			*/
		}
	}
		

	[PunRPC]	
	public void CastVote (int trackSceneNum) {
		trackVotes [trackSceneNum].AddVote (1);
		//Debug.Log (trackVotes [trackSceneNum].tally);

		for (int i = 0; i < trackVotes.Length; i++) {
			if (leadingVote.tally < trackVotes [i].tally) {
				leadingVote = trackVotes [i];
			}
		}
		selectedLevel = leadingVote.name;
		Debug.Log (selectedLevel);
	}
}

[System.Serializable]
public class TrackQuadrant {
	public ModularTrack start, turn, end;
}

[System.Serializable]
public class Vote {
	public string name;
	public int tally;

	public Vote (string voteName, int voteTally) {
		name = voteName;
		tally = voteTally;
	}

	public void AddVote (int value) {
		tally += value;
	}
}
