using UnityEngine;
using System.Collections;

public class SceneManager : MonoBehaviour 
{
	private bool isLoading = false;
	private bool fading = false;
	private string nextScene;
	private SceneTransition fader;
	//private LoadingStatusGUI loadingStatusGui;
	
	public float faderSpeed = 1.0f;
	
	static public void LoadScene(string scene)
	{
		LoadScene(scene, false);
	}

	static public void LoadScene(string scene, bool destroyMusic)
	{
		SceneManager manager = FindObjectOfType<SceneManager>();
		
		if(manager != null)
		{
			manager.LoadSceneInternal(scene, destroyMusic);
		}
		else
		{
			LoadLevel(scene);
		}
	}
	
	void Awake()
	{
		fader = FindObjectOfType<SceneTransition>();
		//loadingStatusGui = FindObjectOfType<LoadingStatusGUI>();
	}

	void Update() 
	{
		#if PROFILE
		var profiler = SmilingProfiler.GetProfiler("SceneManager.Update");
		profiler.StartTiming();
		#endif

		if(isLoading)
		{
			if(!fading && IsLevelReady(nextScene))
			{
				FadeOut();
			}
            //else
            //{
            //    if(loadingStatusGui != null)
            //    {
            //        loadingStatusGui.statusScene = nextScene;
            //        loadingStatusGui.showSceneStatus = true;
            //    }
            //}

			if(fading)
			{
				if(fader == null || fader.completed)
				{
                    //if(destroyMusic)
                    //{
                    //    MenuMusic music = FindObjectOfType<MenuMusic>();
                    //    Destroy(music);
                    //}
					LoadLevel(nextScene);
				}
			}
		}
		
		#if PROFILE
		profiler.StopTiming();
		#endif
	}
	
	public void LoadSceneInternal(string scene, bool destroyMusic)
	{
        nextScene = scene;
        //this.destroyMusic = destroyMusic;
		isLoading = true;
	}

    public void LoadSceneInternal(string scene)
    {
        nextScene = scene;
        //this.destroyMusic = destroyMusic;
        isLoading = true;
    }
    
    private void FadeOut()
	{
        fading = true;
		if(fader != null)
		{
            fader.Fade(false, faderSpeed);
		}
	}
	
	static private void LoadLevel(string sceneName)
	{
		if(Application.CanStreamedLevelBeLoaded(sceneName))
		{
			Application.LoadLevel(sceneName);
		}
	}

	static public bool IsLevelReady(string sceneName)
	{
		return Application.CanStreamedLevelBeLoaded(sceneName);
	}
}
