using UnityEngine;
using System.Collections;

public class GameMemory : MonoBehaviour {

    public static GameMemory control;
    public bool reloadScene = false;
    public Color transitionColor;

    public GameObject playerPrefab;


    public PlayerController playerScript;
    private GameObject backGround;
    private int SceneLoaded;
    public TapDetector tapScript;


	// Use this for initialization
	void Awake () {
	    if (control == null) {
            DontDestroyOnLoad(gameObject);
            control = this;
        }else if (control != this) {
            Destroy(gameObject);
        }

        //playerScript = GetComponentInChildren<PlayerController>();
        tapScript = GetComponent<TapDetector>();
        backGround = GameObject.FindGameObjectWithTag("BackGround");
        SceneLoaded = UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex;

    }

    void Start() {
        startLevel();
    }


    void OnLevelWasLoaded() {
        Debug.Log("New Scene");      
        startLevel();
    }
	
	// Update is called once per frame
	void Update () {
	if (reloadScene) {
            reloadScene = false;
            UnityEngine.SceneManagement.SceneManager.LoadScene(SceneLoaded);
        }

	}

    public void startLevel() {
        if (playerScript != null) {
            playerScript.setHealth(3);
        } else {
            GameObject respawn =  GameObject.FindGameObjectWithTag("Respawn");
            GameObject player = (GameObject) Instantiate(playerPrefab, respawn.transform.position, respawn.transform.rotation);
            DontDestroyOnLoad(player);
            player.transform.parent = transform;
            playerScript = player.GetComponent<PlayerController>();
            tapScript.playerScript = playerScript;
        }


    }

    public void enemyDeath() {
        int enemyCount = GameObject.FindGameObjectsWithTag("Enemy").Length;
        Debug.Log("EnemyDown. Enemies Left: " + enemyCount);
        if (enemyCount -1 == 0) {
            SceneLoaded++;
            UnityEngine.SceneManagement.SceneManager.LoadScene(SceneLoaded);

        }


    }

    public void playerDeath() {
        playerScript = null;
        UnityEngine.SceneManagement.SceneManager.LoadScene(SceneLoaded);
    }


}
