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

public class GameManager : MonoBehaviour {
    [SerializeField] private PawnScript pawnPrefab;
    [SerializeField] private ForcePanelScript forcePanel;
    [SerializeField] private LevelManager levelManagerPrefab;
    [SerializeField] private GameObject levelUI;
    [SerializeField] private GameObject menuPause;
    [SerializeField] private GameObject menuLevelFail;
    [SerializeField] private GameObject menuLevelDone;
    [SerializeField] private GameObject mainMenu;
    [SerializeField] private GameObject splashScreen;
    [SerializeField] private GameObject credits;
    [SerializeField] private Camera mainCamera;

    [SerializeField] private AudioClip fireAudio;
    [SerializeField] private AudioClip waterAudio;

    [SerializeField] private AudioSource buttonEffectAudio;

    public Text safePilgrims;
    public Text alivePilgrims;

    public static GameManager Instance { get { return _instance; } }

    private static GameManager _instance = null;

    private ForceType activeForce = null;
    private LevelManager levelManagerHolder = null;

    public MapGrid map;
    [HideInInspector]
    public int level;
    

    private void Awake() {
        _instance = this;
        
        StartCoroutine(RemoveSplashScreen());
    }

    IEnumerator RemoveSplashScreen()
    {
        yield return new WaitForSeconds(3f);
        RemoveSplashScreenNow();
    }

    public void RemoveSplashScreenNow() {
        if (splashScreen.activeInHierarchy) {
            splashScreen.SetActive(false);
            ShowMainMenu();
        }
    }

    private void Update(){
        if(Input.GetKeyDown(KeyCode.Escape))
        {
            PauseGame(!menuPause.activeInHierarchy);
        }
    }

    public void ShowMainMenu(){
        mainMenu.SetActive(true);
        MusicManager.instance.PlayIntroMusic();
    }

    public void StartGame(){
        

        //level = 2;
        InitilaizeLevel();
    }

    public void ForceActivated(ForceType force) {
        if (activeForce != null) {
            map.ForceDeactivated(activeForce);
        }

        //Debug.LogFormat("Force == ForceType.Wind: " + (force == ForceType.Wind));
        map.ForceActivated(force);
        forcePanel.ButtonClicked(force);
        MusicManager.instance.PlayForceMusic(force);

        if (force == ForceType.Fire) {
            buttonEffectAudio.PlayOneShot(fireAudio);
        } else if (force == ForceType.Water) {
            buttonEffectAudio.PlayOneShot(waterAudio);
        }
    }

    public void InitilaizeLevel() {
        mainMenu.SetActive(false);
        ClearLevel();

        levelManagerHolder = Instantiate(levelManagerPrefab) as LevelManager;
        levelManagerHolder.InitializeLevel();
        UpdateSafeCounter(0);

        levelUI.SetActive(true);

        ForceType[] forces = new ForceType[] { ForceType.Fire, ForceType.Water };
        forcePanel.Initialize(forces);

        mainCamera.transform.position = map.CameraPosition;
        mainCamera.transform.Translate(Vector3.back * map.CameraDistance, Space.Self);
    }

    public void ResetLevel() {
        //does reset need to do something in addition to init?
        InitilaizeLevel();
    }

    public void NextLevel()  {
        level++;
        InitilaizeLevel();
    }

    private void ClearLevel() {
        if (levelManagerHolder != null)
        { DestroyImmediate(levelManagerHolder.gameObject); }

        Time.timeScale = 1;
        menuLevelDone.SetActive(false);
        menuLevelFail.SetActive(false);
        levelUI.SetActive(false);
        menuPause.SetActive(false);
    }

    public void UpdateSafeCounter(int num) {
        safePilgrims.text = string.Format("{0}/{1}", num, LevelManager.instance.goalSafePilgrims);
    }

    public void UpdateAliveCounter(int num)
    {
        alivePilgrims.text = string.Format("{0}", num);
    }

    public void PauseGame(bool toPause) {
        Time.timeScale = System.Convert.ToInt32(!toPause);
        menuPause.SetActive(toPause);
    }

    public void LevelSuccesseded() {
        buttonEffectAudio.Stop();
        MusicManager.instance.PlaySuccessMusic();
        Time.timeScale = 0;
        menuLevelDone.SetActive(true);
        menuLevelFail.SetActive(false);
        menuPause.SetActive(false);
        levelUI.SetActive(false);
    }

    public void LevelFailed() {
        buttonEffectAudio.Stop();
        MusicManager.instance.PlayFailMusic();
        Time.timeScale = 0;
        menuLevelDone.SetActive(false);
        menuLevelFail.SetActive(true);
        menuPause.SetActive(false);
        levelUI.SetActive(false);

    }

    public void ExitLevel() {
        buttonEffectAudio.Stop();
        MusicManager.instance.StopMusic();

        //Show main menu

        ClearLevel();
        ShowMainMenu();
    }

    public void LoadLevel(int levelSelected)
    {
        level = levelSelected;
        StartGame();
    }

    public void ExitGame()
    {
        StartCoroutine(ShowCreditsAndQuit());
    }

    IEnumerator ShowCreditsAndQuit()
    {
        credits.SetActive(true);
        yield return new WaitForSeconds(3f);
        Application.Quit();
    }
}
