using System;
using System.Collections;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using PlayFab;

public class LoginLoader : MonoBehaviour 
{
    [Header("Login Canvases")]
    [SerializeField] GameObject m_loadingCanvas;
    [SerializeField] GameObject m_loginCanvas;
    [SerializeField] GameObject m_oldVersionCanvas;

    [Header("Login Data")]
    [ReadOnly] [SerializeField] PlayerStats m_playerStats;

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

    void Awake() 
    {
        if (PlayFabClientAPI.IsClientLoggedIn()) 
        {
            m_playerStats.GetPlayerStats();
            return;
        }

        m_playerStats = FindObjectOfType<PlayerStats>();

        CheckGameVersion(false);
    }

    async void CheckGameVersion(bool _requireCert = true) 
    {
        UnityWebRequest _request = UnityWebRequest.Get("https://blackrocket.com/files/rocket-kart-racers-version.json");

        if (!_requireCert)
        {
            var cert = new ForceAcceptAll();
            _request.certificateHandler = cert;
        }

        _request.SendWebRequest();

        while (!_request.isDone)
            await Task.Yield();

        GameVersion serverVersion = JsonUtility.FromJson<GameVersion>(_request.downloadHandler.text);

        if (serverVersion == null)
        {
            if (m_debugChannel)
                m_debugChannel.Raise(this, new string[]{
                "Web request failed!",
                "Unable to verify server version. Client may be out of date.",
                "Please download the most recent build from https://blackrocket.egnyte.com/fl/KC08BFYrFF"},
                DebugChannelSO.Severity.Error);

            SetActiveCanvas(m_loginCanvas);

            return;
        }

        // HANDLE OLD VERSION CONVENTIONS //
        #region
        //string editorVersion = PlayerSettings.bundleVersion;
        //double editorVersionDouble = Convert.ToDouble(editorVersion);

        //double serverVersionDouble = Convert.ToDouble(currentVersion.version);
        #endregion

        // DETECT OLD VERSION CONVENTIONS //
        #region
        if (serverVersion.version.Contains("."))
        {
            if (m_debugChannel)
                m_debugChannel.Raise(this,
                new string[]{
                    "Client version validated!",
                    "Server version still using old naming conventions."}
                );

            SetActiveCanvas(m_loginCanvas);
            return;
        }
        #endregion

        // HANDLE NEW VERSION CONVENTIONS //
        #region
        string dateTimeString = serverVersion.version;
        string[] serverSubstrings = dateTimeString.Split('_');
        string[] clientSubstrings = GameVersion.ClientVersion.Split('_');

        if (clientSubstrings.Length != 3 || serverSubstrings.Length != 3)
        {
            if (m_debugChannel)
                m_debugChannel.Raise(this,
                new string[]{
                    "Client version failed to validate!",
                    "Client and Server versions do not use the same naming conventions."}
                );

            SetActiveCanvas(m_oldVersionCanvas);
            return;
        }

        for (int i = 0; i < 3; i++)
            if (int.Parse(serverSubstrings[i]) > int.Parse(clientSubstrings[i]))
            {
                if (m_debugChannel)
                    m_debugChannel.Raise(this,
                    new string[]{
                        "Client version failed to validate!",
                        "Please update to the latest version."},
                    DebugChannelSO.Severity.Error
                    );

                SetActiveCanvas(m_oldVersionCanvas);
                return;
            }

        if (m_debugChannel)
            m_debugChannel.Raise(this,
            new string[]{
                "Client version validated!",
                "Server version: " + dateTimeString + " | Client version: " + GameVersion.ClientVersion}
            );

        SetActiveCanvas(m_loginCanvas);
        #endregion
    }

    void SetActiveCanvas(GameObject canvas) 
    {
        m_loadingCanvas.SetActive(canvas == m_loadingCanvas);
        m_loginCanvas.SetActive(canvas == m_loginCanvas);
        m_oldVersionCanvas.SetActive(canvas == m_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 static string ClientVersion { get { return "2022_06_18"; } }
    public string version;

    public override string ToString()
    {
        return "version : " + version;
    }
}