using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using PlayFab;

public class LoginLoader : MonoBehaviour {

    public GameObject loadingCanvas;
    public GameObject loginCanvas;
    public GameObject oldVersionCanvas;

    Double version = 1.1;

    public PlayerStats playerStats;

    void Awake() {
        if (PlayFabClientAPI.IsClientLoggedIn()) {
            playerStats.GetPlayerStats();
            return;
        }
        //SetActiveCanvas(loginCanvas);
        //Debug.Log("Test!");
        StartCoroutine(CheckGameVersion());
    }

    IEnumerator CheckGameVersion() {
        UnityWebRequest www = UnityWebRequest.Get("https://blackrocket.com/files/rocket-kart-racers-version.json");
        UnityWebRequestAsyncOperation response = www.SendWebRequest();

        yield return response;

        GameVersion currentVersion = JsonUtility.FromJson<GameVersion>(www.downloadHandler.text);

        Double currentVersionDouble = Convert.ToDouble(currentVersion.version);

        Debug.LogError("Client version: " + version.ToString());
        Debug.LogError("Server version: " + currentVersionDouble.ToString());

        if (currentVersionDouble > version) {
        Debug.LogError("Client version: " + version.ToString());
            Debug.LogError("Version is out of date! Please update to the latest version.");
            SetActiveCanvas(oldVersionCanvas);
        }
        else {
            Debug.LogError("Version is up to date!");
            SetActiveCanvas(loginCanvas);
        }
    }

    void SetActiveCanvas(GameObject canvas) {
        loadingCanvas.SetActive(canvas == loadingCanvas);
        loginCanvas.SetActive(canvas == loginCanvas);
        oldVersionCanvas.SetActive(canvas == oldVersionCanvas);
    }

    public void GoToDownloadPage() {
#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN
        Application.OpenURL("https://www.blackrocket.com/esports");
#else
        Application.ExternalEval("window.open(\"https://www.blackrocket.com/esports\")");
#endif
    }
}

[Serializable]
public class GameVersion {
    public string version;
}
