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

[ExecuteAlways]
public class DoNotDelete : MonoBehaviour {

	#if UNITY_EDITOR

	public static bool EditorApplicationQuit = false;

	static bool WantsToQuit() {
		EditorApplicationQuit = true;
		return true;
	}

	// Initialize fireing an event on quit Unity
	void OnEnable() {
		EditorApplication.wantsToQuit += WantsToQuit;
	}

	void OnDestroy () {
		if(Time.frameCount == 0 || EditorApplicationQuit || !this.enabled){
			return;
		}

		if (EditorApplication.isPlayingOrWillChangePlaymode || (!EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying)) {
			return;
		}

		if (EditorUtility.DisplayDialog("Essential Track Piece Error", "Cannont delete this object because it is essentail.", "Ok")) {
			StopDelete ();
			return;
		} else {
			StopDelete ();
			return;
		}
	}

	void StopDelete () {

		var go = this.gameObject;
		var pos = go.transform.position;
		var rot = go.transform.rotation;

		var sceneCurrent = SceneManager.GetActiveScene();
		SceneManager.SetActiveScene(go.scene);

		var goCopy = Instantiate(go);
		goCopy.transform.parent = go.transform.parent;
		goCopy.transform.localPosition = pos;
		goCopy.transform.localRotation = rot;

		goCopy.name = go.name;
		goCopy.SetActive(true);

		SceneManager.SetActiveScene(sceneCurrent);
		Selection.activeGameObject = goCopy;
	}
	#endif
}
