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.2;

    public PlayerStats playerStats;

    [Header("Debug")]
    [SerializeField] DebugChannelSO m_debugChannel;

    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 =  currentVersion != null ? Convert.ToDouble(currentVersion.version) : version;

        if (m_debugChannel)
        {
            m_debugChannel.Raise(this, "Client version: " + version.ToString(), DebugChannelSO.Severity.Error);
            m_debugChannel.Raise(this, "Server version: " + currentVersionDouble.ToString(), DebugChannelSO.Severity.Error);
        }

        if (currentVersionDouble > version)
        {
            if (m_debugChannel)
            {
                m_debugChannel.Raise(this, "Client version: " + version.ToString(), DebugChannelSO.Severity.Error);
                m_debugChannel.Raise(this, "Version is out of date! Please update to the latest version.", DebugChannelSO.Severity.Error);
            }
            SetActiveCanvas(oldVersionCanvas);
        }
        else {
            if (m_debugChannel)
                m_debugChannel.Raise(this, "Version is up to date!", DebugChannelSO.Severity.Error);
            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;
}
