using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
	public static GameManager instance { get; private set; }
	int turnCount;

	public enum GameState
	{
		InitialSetup,
		SetNewGods,
		ChooseAProperty,
		AnimatingToSacrifice,
		SeeEffectsOfChoice,
		WaitingForGod,
		BuildingRefresh,
		GameOver
	};

	public GameState currentGameState;

	void Awake()
	{
		GameObject VengeanceIcon = GameObject.Find("HeartIcon");
		VengeanceIcon.GetComponent<Image>().enabled = false;

		instance = this;
	}

	public void changeState(GameState newState)
	{
		Debug.Log("Changing state: "+newState.ToString());

		currentGameState = newState;

		switch (currentGameState)
		{
		case GameState.InitialSetup:
			turnCount = 0;
			GameOverScreen.instance.toggleScreenVisibility(false);
			BuildingManager.instance.addStartingBuildings();
			GodManager.instance.setStartingGods();
			changeState(GameState.SetNewGods);
			AudioController.instance.audioStateChange(AudioController.audioState.mainLoop);
			break;

		case GameState.SetNewGods:
			GodManager.instance.checkForNewGod();
			GodManager.instance.updateGodState(GodManager.godState.enterScreen);
			BuildingManager.instance.toggleBuildingButtons(false);
			AudioController.instance.audioStateChange(AudioController.audioState.mainLoop);
			break;

		case GameState.ChooseAProperty:
			BuildingManager.instance.toggleBuildingButtons(true);
			break;

		case GameState.AnimatingToSacrifice:
			BuildingManager.instance.toggleBuildingButtons(false);
			GameObject Man = GameObject.Find("Priest");
			Man.GetComponent<PriestManager>().GetSacrifice();
			AudioController.instance.audioStateChange(AudioController.audioState.volcanoBuildUp);
			break;

		case GameState.SeeEffectsOfChoice:
			GodManager.instance.updateGodState(GodManager.godState.delayBeforeProcessingSacrifice);
			changeState(GameState.WaitingForGod);
			AudioController.instance.playSFX(AudioController.audioClips.splash);
			break;

		case GameState.WaitingForGod:
			if (GodManager.instance.currentState == GodManager.godState.finishedSacrifice)
			{
				changeState(GameState.BuildingRefresh);
			}
			break;

		case GameState.BuildingRefresh:
			BuildingManager.instance.checkForChanceOfNewBuilding();

			turnCount++;
			if (BuildingManager.instance.areAllBuildingsOnFire())
			{
				changeState(GameState.GameOver);
			}
			else
			{
				changeState(GameState.SetNewGods);
			}
			break;

		case GameState.GameOver:
			GodManager.instance.updateGodState(GodManager.godState.leaveScreen);
			GameOverScreen.instance.toggleScreenVisibility(true);
			break;

		default:
			Debug.LogError("Unhandled state error: " + newState);
			break;
		}
	}

	void Start()
	{
		changeState(GameState.InitialSetup);
	}
}
