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

public class AssetHandling : SearchableEditorWindow {

	[System.Serializable]
	public enum OptionType { Export, Import };

	public static List<string> levels, spells, wands;
	public static List<bool> toggleLevels, toggleWands, toggleSpells;
	public static List<string> defaultNames = new List<string> { "First Name", "Last Initial" };
	public int teamMemberCount = 1;

	public OptionType optionType;
	public bool allFiles = false;

	public List<string> exportFirstName = new List<string>(), exportLastInitial = new List<string>();
	public string exportName = "My Battle Maps", additionalChars = "";
	const string randomChars = "BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxYyZz0123456789";
	string[] removeChars = { "/", "\\", "\"", ":", "?", "<", ">", "|", "*", "~", ".", "@", "#", "$", "%", "^", "(", ")", "{", "}", "[", "]", "`", ";", ",", "!", "'", "+", "=" };

	public Vector2 levelScrollSpot, wandScrollSpot, spellScrollSpot, urlRect;

	[MenuItem("Battle Royale/Export-Import Options/Export Asset Packs", false, 0)]
	public static void SelectAssetsToExport() {
		AssetHandling window = GetWindow<AssetHandling>("Battle Royale Exporter");
		window.optionType = OptionType.Export;
		window.minSize = new Vector2(600, 400);
		window.maxSize = new Vector2(window.minSize.x, 4000);
    }
	
	[MenuItem("Battle Royale/Export-Import Options/Export Asset Packs", true, 0)]
    public static bool FindAssets()
    {
		Debug.Log("Finding!");
		string[] tempLevelNames = Directory.GetFiles(Application.dataPath + "/Levels");
		levels = new List<string>();
		toggleLevels = new List<bool>();

		if (tempLevelNames.Length < 1) {
			Debug.Log("No levels available to export.");
            return false;
        }

		foreach (string level in tempLevelNames) {
			Debug.Log("Found " + level);
			if (!level.Contains(".meta") && !level.Contains(".txt")) {
				#if UNITY_EDITOR_WIN
				string levelName = level.Substring(level.LastIndexOf('\\') + 1);
				#else
				string levelName = level.Substring(level.LastIndexOf('/') + 1);
				#endif
				levels.Add(levelName.Replace(".prefab", ""));
				toggleLevels.Add(false);
			}
        }
        
		string[] tempWandNames = Directory.GetFiles(Application.dataPath + "/Prefabs/Resources/Custom Wands");
		wands = new List<string>();
		toggleWands = new List<bool>();

		if (tempWandNames.Length < 1) {
			Debug.Log("No Custom Wands");
		}

		foreach (string wand in tempWandNames) {
			if (!wand.Contains(".meta") && !wand.Contains(".txt")) {
				#if UNITY_EDITOR_WIN
				string wandName = wand.Substring(wand.LastIndexOf('\\') + 1);
				#else
				string wandName = wand.Substring(wand.LastIndexOf('/') + 1);
				#endif
				wands.Add(wandName.Replace(".prefab", ""));
				toggleWands.Add(false);
			}
		}

		string[] tempSpellNames = Directory.GetFiles(Application.dataPath + "/Spells");
		spells = new List<string>();
		toggleSpells = new List<bool>();

		if (tempSpellNames.Length < 1) {
			Debug.Log("No Custom Spells");
		}

		foreach (string mat in tempSpellNames) {
			if (!mat.Contains(".meta") && !mat.Contains(".txt")) {
				#if UNITY_EDITOR_WIN
				string matName = mat.Substring(mat.LastIndexOf('\\') + 1);
				#else
				string matName = mat.Substring(mat.LastIndexOf('/') + 1);
				#endif
				spells.Add(matName.Replace(".asset", ""));
				toggleSpells.Add(false);
			}
		}

		if (tempLevelNames.Length < 1 && tempSpellNames.Length < 1 && tempWandNames.Length < 1) {
			return false;
        }

		return true;
	}

	[MenuItem("Battle Royale/Export-Import Options/Import Asset Pack", false)]
	public static void SelectAssetsToImport()
    {
		string selectedFile = EditorUtility.OpenFilePanelWithFilters("Select Assets to Import", "Asset Packages", new string[] { "Unity Asset Package", "unitypackage" });

		if (selectedFile != "")
        {
			AssetDatabase.ImportPackage(selectedFile, true);
        }
    }

	void OnGUI()
    {
		GUIStyle myStyle = new GUIStyle(GUI.skin.textField);
		myStyle.alignment = TextAnchor.MiddleCenter;

		if (optionType == OptionType.Export)
        {
			// Top Buffer
			GUILayout.Space(6);

			GUILayout.BeginVertical();
            #region

				// Export Data Block
				GUILayout.BeginHorizontal();
				#region
			
					// Left Buffer
					GUILayout.Space(6);

					GUILayout.BeginVertical("Team Info", "window", GUILayout.Width((position.width / 2) - 10));
					#region

						GUILayout.Space(5);

						GUILayout.Label("Team Size", EditorStyles.boldLabel);

						// Team Member Count
						GUILayout.BeginHorizontal();
						#region

							GUILayout.Space(5);

							myStyle.fixedWidth = 30;
							myStyle.margin.top = 7;

							teamMemberCount = EditorGUILayout.IntField(teamMemberCount, myStyle);
							teamMemberCount = Mathf.Clamp(teamMemberCount, 1, 5);

							GUILayout.FlexibleSpace();

						#endregion
						GUILayout.EndHorizontal();

						// Team Member Names
						for (int i = 0; i < teamMemberCount; i++)
						{
							while (exportFirstName.Count != teamMemberCount)
							{
								if (exportFirstName.Count < teamMemberCount)
								{
									exportFirstName.Add(defaultNames[0]);
								}
								else
								{
									exportFirstName.RemoveAt(teamMemberCount - 1);
								}
							}
							while (exportLastInitial.Count != teamMemberCount)
							{
								if (exportLastInitial.Count < teamMemberCount)
								{
									exportLastInitial.Add(defaultNames[1]);
								}
								else
								{
									exportLastInitial.RemoveAt(teamMemberCount - 1);
								}
							}

							GUILayout.Label("Team Member " + (i + 1).ToString(), EditorStyles.boldLabel);

							exportFirstName[i] = GUILayout.TextField(exportFirstName[i]);
							exportLastInitial[i] = GUILayout.TextField(exportLastInitial[i]);
						}

					#endregion
					GUILayout.EndVertical();

					GUILayout.FlexibleSpace();

					GUILayout.BeginVertical("Select Files to Export", "window", GUILayout.Width((position.width / 2) - 10));
					#region

						GUILayout.Space(5);

						GUILayout.Label("Custom Levels", EditorStyles.boldLabel);

						if (levels == null)
						{
							Debug.LogWarning("Asset Exporter: Levels list has not been initialized. Please Wait.");
							return;
						}

						if (levels.Count == 0)
						{
							GUILayout.Label("Uh oh! We couldn't find any Level Prefabs.", EditorStyles.wordWrappedLabel);

							GUILayout.Space(10);

							GUILayout.Label("Make sure your prefabs are placed in the Levels folder.", EditorStyles.wordWrappedLabel);

							GUILayout.Space(10);

							GUILayout.Label("You can access the folder by clicking 'Window' at the top of your screen, then 'General -> Project'. The Levels folder can be found in the default 'Assets' directory.", EditorStyles.wordWrappedLabel);

							GUILayout.Space(10);

							GUILayout.Label("Ask your instructor for help moving your p[refabs, or you may contact one of our Tech Support agents by clicking the button below:", EditorStyles.wordWrappedLabel);

							GUILayout.Space(10);

							if (GUILayout.Button("Black Rocket Support"))
							{
								Application.OpenURL("https://www.blackrocket.com/help");
							}
						}
						else
						{
							levelScrollSpot = GUILayout.BeginScrollView(levelScrollSpot, GUILayout.Width(position.width / 2 - 20), GUILayout.Height(100));
							#region

								for (int i = 0; i < levels.Count; i++)
								{
									toggleLevels[i] = GUILayout.Toggle(toggleLevels[i], levels[i]);
								}

							#endregion
							GUILayout.EndScrollView();

							GUILayout.Space(5);

							GUILayout.Label("Custom Wands", EditorStyles.boldLabel);

							if (wands.Count > 0)
							{
								wandScrollSpot = GUILayout.BeginScrollView(wandScrollSpot, GUILayout.Width(position.width / 2 - 20), GUILayout.Height(60));
								#region

									for (int i = 0; i < wands.Count; i++)
									{
										toggleWands[i] = GUILayout.Toggle(toggleWands[i], wands[i]);
									}

								#endregion
								GUILayout.EndScrollView();
							}
							else
							{
								GUILayout.Label("No custom wands found...", EditorStyles.wordWrappedLabel);

								GUILayout.Space(10);

								GUILayout.Label("Custom wands should be placed in the 'Assets -> Wands' folder. Avoid using the word 'Default' in the file name.", EditorStyles.wordWrappedLabel);
							}

							GUILayout.Space(5);

							GUILayout.Label("Custom Spells", EditorStyles.boldLabel);

							if (spells.Count > 0)
							{
								spellScrollSpot = GUILayout.BeginScrollView(spellScrollSpot, GUILayout.Width(position.width / 2 - 20), GUILayout.Height(60));
								#region

									for (int i = 0; i < spells.Count; i++)
									{
										toggleSpells[i] = GUILayout.Toggle(toggleSpells[i], spells[i]);
									}

								#endregion
								GUILayout.EndScrollView();
							}
							else
							{
								GUILayout.Label("No custom spells found...", EditorStyles.wordWrappedLabel);

								GUILayout.Space(10);

								GUILayout.Label("Custom spells have not been implemented yet. Coming soon!", EditorStyles.wordWrappedLabel);
							}
						}

					#endregion
					GUILayout.EndVertical();

					GUILayout.Space(6);	// Right Buffer

				#endregion
				GUILayout.EndHorizontal();

				GUILayout.Space(10);

				myStyle = new GUIStyle(GUI.skin.button);
				myStyle.fontStyle = FontStyle.Bold;

				// Initialize Export Button
				if (GUILayout.Button("Export Selected Assets", myStyle, GUILayout.Height(30), GUILayout.Width(position.width - 10)))
				{
					if (teamMemberCount == 0)
					{
						EditorUtility.DisplayDialog("Missing Team Members", "Asset Exports must be submitted with at least one member", "Ok");
						return;
					}

					bool levelIncluded = false;

					foreach (bool toggle in toggleLevels)
					{
						if (toggle)
						{
							levelIncluded = true;
						}
					}

					if (!levelIncluded)
					{
						EditorUtility.DisplayDialog("Missing Level Assets", "Asset Exports must be submitted with at least one level.", "Ok");
						return;
					}

					EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());

					AdjustExportName();

					List<string> selectedAssetPaths = new List<string>();

					for (int i = 0; i < toggleLevels.Count; i++)
					{
						if (toggleLevels[i])
						{
							selectedAssetPaths.Add("Assets/Levels/" + levels[i] + ".prefab");
							Debug.Log("Added " + "Assets/Levels/" + levels[i] + ".prefab");

							selectedAssetPaths.Add("Assets/Do Not Edit OR Delete/Terrains/" + levels[i] + " Terrain.asset");
							Debug.Log("Added " + "Assets/Do Not Edit OR Delete/Terrains/" + levels[i] + " Terrain.asset");
						}
					}

					for (int i = 0; i < toggleWands.Count; i++)
					{
						if (toggleWands[i])
						{
							selectedAssetPaths.Add("Assets/Wands/" + wands[i] + ".prefab");
							Debug.Log("Added " + "Assets/Wands/" + wands[i] + ".prefab");
						}
					}

					for (int i = 0; i < toggleSpells.Count; i++)
					{
						if (toggleSpells[i])
						{
							selectedAssetPaths.Add("Assets/Materials/" + spells[i] + ".mat");
							Debug.Log("Assets/Materials/" + spells[i] + ".mat");
						}
					}

					string[] exportStrings = selectedAssetPaths.ToArray();

					foreach(string export in exportStrings)
					{
						Debug.Log("Packaging " + export);
					}

					string filename = exportName + ".unitypackage";

					AssetDatabase.ExportPackage(exportStrings, "Asset Packages/" + filename, ExportPackageOptions.Interactive);

					this.Close();
				}

				// Bottom Buffer
				GUILayout.Space(6);

			#endregion
			GUILayout.EndVertical();
		}
        else if(optionType == OptionType.Import) {

        }

        Repaint();
    }

	void AdjustExportName()
    {
		foreach (string c in removeChars)
        {
			for (int i = 0; i < teamMemberCount; i++)
            {
				exportFirstName[i] = exportFirstName[i].Replace(c, string.Empty).ToLower();
				exportFirstName[i] = UppercaseFirst(exportFirstName[i]);

				exportLastInitial[i] = exportLastInitial[i].Substring(0, 1).Replace(c, string.Empty).ToUpper();
            }
        }

		string combinedNames = "";

		for (int i = 0; i < teamMemberCount; i++)
        {
			combinedNames = combinedNames + exportFirstName[i] + exportLastInitial[i] + "_";
        }

		additionalChars = "";

		for (int i = 0; i < 6; i++)
        {
			additionalChars += randomChars[Random.Range(0, randomChars.Length - 1)];
        }

		exportName = combinedNames + System.DateTime.Now.ToString("MMMM").Substring(0, 3) + System.DateTime.Now.ToString("dd_hh-mm");
    }

	string UppercaseFirst(string s)
    {
		if (string.IsNullOrEmpty(s))
        {
			return string.Empty;
        }
		char[] a = s.ToCharArray();
		a[0] = char.ToUpper(a[0]);
		return new string(a);
    }
}
