using UnityEngine;
using System.Collections;
using System;
using System.Linq;

#if UNITY_EDITOR
using UnityEditor.SceneManagement;
using UnityEditor;
using System.Threading;
#endif

[ExecuteInEditMode]
public class SceneLoader : MonoBehaviour
{
	#if UNITY_EDITOR
	public static bool ignoreAwake = false;

	public SceneSetupInternal[] scenes;

	void Start ()
	{
		if (Application.isPlaying == false) {
			if (ignoreAwake == false) {
				this.LoadSetup ();
			} else {
				ignoreAwake = false;
			}
		} else {
			ignoreAwake = true;
		}
	}

	public void LoadSetup ()
	{
		this.LoadSetupCoroutine ();
	}

	private void LoadSetupCoroutine ()
	{
		ignoreAwake = true;
		EditorSceneManager.RestoreSceneManagerSetup (this.scenes.Select (ss => ss.ToSceneSetup ()).ToArray ());
	}

	public void SaveSetup ()
	{
		this.scenes = EditorSceneManager.GetSceneManagerSetup ().Select (ss => SceneSetupInternal.FromSceneSetup (ss)).ToArray ();
		EditorSceneManager.MarkSceneDirty (this.gameObject.scene);
	}

	[Serializable]
	public class SceneSetupInternal
	{
		public static SceneSetupInternal FromSceneSetup (SceneSetup ss)
		{
			var result = new SceneSetupInternal ();
			result.isActive = ss.isActive;
			result.isLoaded = ss.isLoaded;
			result.path = ss.path;
			return result;
		}

		public string path;
		public bool isLoaded;

		[HideInInspector]
		public bool isActive;

		public SceneSetup ToSceneSetup ()
		{
			var result = new SceneSetup ();
			result.isActive = this.isActive;
			result.isLoaded = this.isLoaded;
			result.path = this.path;
			return result;
		}
	}
	#endif
}
