using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
using UnityEngine.Animations;
using UnityEditor;

public class LoadTrackWindow : SearchableEditorWindow {

	public static List<string> trackNames;
	public Vector2 scrollSpot;

	[MenuItem("Rocket Kart Racers/Load Track", false, 2)]
	public static void LoadTrack () {
		LoadTrackWindow window = GetWindow<LoadTrackWindow> ("Load Track");
	}

	[MenuItem("Rocket Kart Racers/Load Track", true)]
	public static bool FindTracks () {
		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") && track.Contains (".unity") ) {
				#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", ""));
			}
		}

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

		return true;
	}

	// Update is called once per frame
	void OnGUI () {
		scrollSpot = GUILayout.BeginScrollView (scrollSpot, GUILayout.Width (position.width), GUILayout.Height (position.height));
		GUILayout.Label ("Select Track to Load...");
		if (FindTracks()) {
			for (int i = 0; i < trackNames.Count; i++) {
				//Debug.Log (trackNames [i]);
				if (GUILayout.Button (trackNames [i])) {
					EditorSceneManager.OpenScene ("Assets/Racetrack Scenes/" + trackNames [i] + ".unity", OpenSceneMode.Single);
					this.Close ();
				}
			}

		// This is here as a fail safe in case something isn't caught in the boolean check
		} else {
			if (EditorUtility.DisplayDialog ("No Tracks Error", "No tracks have been created yet. Please create a track in order to start building.", "Ok")) {
				this.Close ();
			}
		}
		GUILayout.EndScrollView ();
	}
}
