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

public class GameLogicScript : MonoBehaviour {

	private float age = 0.0f;
	private int sceneIndex = -1;
	public PlugScript gameStarter;
	private bool gameEnded = false;
	private Light projector;
	public Texture cookieWin;
	public Texture cookieLose;


	void Awake(){
		DontDestroyOnLoad (this.gameObject);
	}

	void Start () {
		sceneIndex = 0;
	}

	void Update () {
		age += Time.deltaTime;

		if (GameObject.FindGameObjectsWithTag ("GameController").Length >= 2) {
			foreach (GameObject logic in GameObject.FindGameObjectsWithTag ("GameController")) {
				if (logic.GetComponent<GameLogicScript> ().age <= 5.0f) {
					Destroy (logic);
				}
			}
		}

		if (sceneIndex == 0) {
			if (gameStarter.pluggedIn) {
				SceneManager.LoadScene ("Game");
				sceneIndex += 1;
			}
		}

		if (Input.GetKeyDown (KeyCode.Escape)) {
			if (gameEnded) {
				Reset ();
			} else {
				Application.Quit ();
			}
		}
	}


	public void Win(){
		gameEnded = true;
		projector = GameObject.Find ("Spotlight").GetComponent<Light>();
		projector.cookie = cookieWin;
		projector.color = Color.cyan;
	}

	public void Lose(){
		gameEnded = true;
		projector = GameObject.Find ("Spotlight").GetComponent<Light>();
		projector.cookie = cookieLose;
		projector.color = Color.red;
	}

	public void Reset(){
		SceneManager.LoadScene ("Menu");
		gameStarter = GameObject.Find ("Plug_Starter").GetComponent<PlugScript> ();
		gameStarter.pluggedIn = false;
		sceneIndex = 0;
	}
}
