using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using com.deeperbeige.lib;
using Holoville.HOTween;

// Runs the game
namespace com.deeperbeige.whiteout
{
    public class Game : MonoBehaviour
    {
		public  Level level { get; set; }

		private GameObject playerHolder;
		private List<Player> players;
		private GameObject ui;
		private GameObject playersUI;
		private GameObject pauseScreen;

        void Start()
        {
			App.inst.create();
			level = Levels.Find(App.inst.levelID);

            App.inst.meshParams.CreateLandscape ();

			ui = GameObjects.FindAnywhere("UI Root");
			pauseScreen = GameObjects.FindNested(ui, "Pause");

			playerHolder = GameObjects.FindAnywhere("Players");
			GameObjects.FindNested(playerHolder, "Players_1").SetActive(App.inst.players == 1 ? true : false);
			GameObjects.FindNested(playerHolder, "Players_2").SetActive(App.inst.players == 2 ? true : false);
			GameObjects.FindNested(playerHolder, "Players_4").SetActive(App.inst.players == 4 ? true : false);

			GameObjects.FindNested(ui, "Players_1").SetActive(App.inst.players == 1 ? true : false);
			GameObjects.FindNested(ui, "Players_2").SetActive(App.inst.players == 2 ? true : false);
			GameObjects.FindNested(ui, "Players_4").SetActive(App.inst.players == 4 ? true : false);

			players = new List<Player>();
			foreach (Player player in Resources.FindObjectsOfTypeAll<Player>())
			{
				if (! player.gameObject.activeInHierarchy) continue;

				string name = player.transform.parent.name;
				players.Add(player);
				player.playerID = int.Parse(name.Substring(name.Length - 1));
				player.Init();
			}

			Events.Listen(Transition.EVENT_PRE_CHANGE, OnSceneChange, true);
			Events.Listen(Events.EVENT_RESIZE_LATE,    OnResize,      true);
			Events.Listen(Events.EVENT_UI_DOUBLE_BACK, OnClickQuit,   true);
		}
        
		private void OnSceneChange()
		{
			HOTween.Kill();
		}
        
		private void OnResize()
		{
		}

		private void OnClickQuit()
		{
			Time.timeScale = 1;
			Transition.To("levelselect");
		}
		
		private void OnClickRestart()
		{
			Time.timeScale = 1;
			Transition.To("reset");
		}
		
		private void OnClickResume()
		{
			Time.timeScale = 1;
			pauseScreen.SetActive(false);
		}

		private void OnClickPause()
		{
			Time.timeScale = 0;
			pauseScreen.SetActive(true);
		}

		void Update ()
        {
		}
    }
}