﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using System.IO;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif

[ExecuteInEditMode]
public class LevelEditor : MonoBehaviour {

	[HideInInspector]
	public bool levelError;

	[BoolToButton("savePrefab", "Save Prefab")]
	public bool savePrefab = false;
	// Here for spacing rather than actual functionality
	[BoolToButton("", "")]
	public bool emptyBool = false;

	[BoolToButton("exportLevel", "Export Prefab")]
	public bool exportLevel = false;
	// Here for spacing rather than actual functionality
	[BoolToButton("", "")]
	public bool emptyBool2 = false;

	public bool autoSaveLevel = true;
	[VariableToggle("autoSaveLevel", false)]
	public float autoSaveTimeValue = 60f;

	float autoSaveTimer = 0f;
	bool initialSave = false;
	[HideInInspector]
	public bool holdUpdate = true;

	string myLevelName = "";

	#if UNITY_EDITOR
	void Awake () {
		initialSave = true;
		exportLevel = false;
		holdUpdate = true;
	}

	void Start () {
		exportLevel = false;
	}

	void Update () {

		return;

		autoSaveTimeValue = Mathf.Clamp (autoSaveTimeValue, 15f, 300f);
		
		if (EditorApplication.isPlayingOrWillChangePlaymode) {
			// Don't do anything in playmode
		} else {

			// delay saving and other updates
			if (holdUpdate) {
				holdUpdate = false;
				return;
			}

			autoSaveTimer += Time.deltaTime;

			if((autoSaveLevel && autoSaveTimer > autoSaveTimeValue) || (initialSave && autoSaveTimer > 1.5f)){
				SavePrefab (true);
				autoSaveTimer = 0f;
			}

			SavePrefab (savePrefab);
		}
	}

	void SavePrefab (bool save) {

		if (gameObject.activeInHierarchy && save) {
			
			if (initialSave) {
				myLevelName = gameObject.name;
				initialSave = false;
			}

			if (myLevelName != gameObject.name) {
				gameObject.name = myLevelName;
			}

			if (AssetDatabase.IsValidFolder ("Assets/Levels")) {
				Object newLevelPrefab = PrefabUtility.SaveAsPrefabAsset (gameObject, "Assets/Levels/" + gameObject.name + ".prefab");
				PrefabUtility.SaveAsPrefabAssetAndConnect (gameObject, "Assets/Levels/" + gameObject.name + ".prefab", InteractionMode.AutomatedAction);
				PrefabUtility.UnpackPrefabInstance (gameObject, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
				EditorSceneManager.SaveScene (EditorSceneManager.GetActiveScene ());
			} else {
				Debug.Log ("The Levels folder has been moved or deleted, please return the Levels folder inside the Assets folder or create a new Levels folder.");
			}
		}
		savePrefab = false;
	}
	#endif
}
