using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LevelController : MonoBehaviour
{

    public static LevelController Instance;

    public GameObject PlayerHuman;
    public Vector2 StartPositionHuman;

    public GameObject PlayerGhost;
    public Vector2 StartPositionGhost;

    /// <summary>
    /// The index of the current level
    /// </summary>
    public int CurrentLevel;

    /// <summary>
    /// The name of the current level
    /// </summary>
    private string _currentScene;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(this);
        }
    }

	// Use this for initialization
	void Start ()
	{
	    for (int i = 1; i < SceneManager.sceneCount; i++)
	    {
	        SceneManager.UnloadSceneAsync(SceneManager.GetSceneAt(i));

	    }

        LoadLevel(CurrentLevel);
    }
	
	// Update is called once per frame
	void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
        else if (Input.anyKeyDown)
        {
            for (int i = 1; i < 10; i++)
            {
                if (Input.GetKeyDown("" + i))
                {
                    LoadLevel(i);
                    break;
                }
            }
        }
    }

    public void LoadLevel(int level)
    {
        if (!string.IsNullOrEmpty(_currentScene) && SceneManager.sceneCount > 1)
        {
            print("Unloading scene: " + _currentScene);
            SceneManager.UnloadSceneAsync(_currentScene);
        }

        ResetPlayers();

        print("Loading scene: " + "Level " + level);
        SceneManager.LoadScene("Level " + level, LoadSceneMode.Additive);

        _currentScene = "Level " + level;
        CurrentLevel = level;
    }

    public void NextLevel()
    {
        LoadLevel(++CurrentLevel);
    }

    public void ReloadLevel()
    {
        LoadLevel(CurrentLevel);
    }

    public void ResetPlayers()
    {
        PlayerHuman.transform.position = new Vector3(StartPositionHuman.x, StartPositionHuman.y, -1);
        PlayerGhost.transform.position = new Vector3(StartPositionGhost.x, StartPositionGhost.y, -1);
    }
}
