using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;


[ExecuteInEditMode]
public class CreateLevelPrefab : MonoBehaviour {
	[HideInInspector]
	public GameObject defaultLevel, defaultPlane;
	public string levelName;
	[HideInInspector]
	public string meshName;
	[BoolToButton("makeLevel")]
	public bool makeLevel = false;
	// Here for spacing rather than actual functionality
	[BoolToButton("")]
	public bool destroyMe = false;

	const string randomChars = "BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxYyZz0123456789";
	string[] removeChars = { "/", "\\", "\"", ":", "?", "<", ">", "|", "*", "~", ".", "@", "#", "$", "%", "^", "(", ")", "{", "}", "[", "]", "`", ";", ",", "!", "'", "+", "=" };

	void Awake () {
		HideHierarchyElements ();
	}

	void OnValidate () {
		//makeLevel = false;

		if (!defaultLevel) {
			defaultLevel = (GameObject) AssetDatabase.LoadAssetAtPath ("Assets/Do Not Edit OR Delete/Core Prefabs/In Use/Scene Setup/Default Level Prefab.prefab", typeof(GameObject));
		}

		//levelName = something

		foreach (string c in removeChars) {
			levelName = levelName.Replace (c, string.Empty);
		}

		if (gameObject.activeInHierarchy && makeLevel && defaultLevel) {

			string additionalChars = "";

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

			GameObject myLevel = GameObject.Instantiate (defaultLevel);
			myLevel.name = levelName + "_" + additionalChars;
			meshName = myLevel.name;

			destroyMe = true;

			UnityEditor.EditorApplication.delayCall += () => {DestroyImmediate(gameObject);};

		}
	}

	void Update () {
		if (transform.childCount > 0) {
			foreach (Transform child in transform) {
				child.parent = null;
			}
		}
	}

	void OnDestroy () {
		if (destroyMe) {

			string terrainPlanePath = "Assets/Do Not Edit OR Delete/Terrain Planes/" + meshName + " Mesh.mesh";

			FileUtil.CopyFileOrDirectory ("Assets/Do Not Edit OR Delete/Core Prefabs/In Use/Scene Setup/Terrain Plane Mesh.mesh", terrainPlanePath);
		
			AssetDatabase.Refresh ();

			GameObject myPlane = GameObject.Instantiate (defaultPlane);
			myPlane.name = meshName + " Terrain Plane";
			myPlane.GetComponent<MeshFilter> ().sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh> (terrainPlanePath);
			myPlane.GetComponent<MeshCollider> ().sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh> (terrainPlanePath);

			AssetDatabase.Refresh ();
		}
	}

	void HideHierarchyElements () {
		GameObject canvases = GameObject.FindGameObjectWithTag ("Safe");
		if (canvases)
			canvases.hideFlags = HideFlags.None;
	}
}
#endif
