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

public class LoginLoader : MonoBehaviour {

    // CANVASES //
    #region
    [Header("Canvases")]
    public GameObject loadingCanvas;
    public GameObject loginCanvas;
    public GameObject oldVersionCanvas;
    #endregion

    // RETRIEVED DATA //
    #region
    [Header("Retrieved Stats")]
    public PlayerStats playerStats;
    #endregion

    // DEBUG //
    #region
    [Header("Debug")]
    [SerializeField] DebugChannelSO m_debugChannel;
    [SerializeField] bool m_requireCert = true;
    #endregion

	string _clientVersion = "2022_06_18";

    void Awake() {
        if (PlayFabClientAPI.IsClientLoggedIn()) {
            playerStats.GetPlayerStats();
            return;
        }
        StartCoroutine(CheckGameVersion());
    }

    IEnumerator CheckGameVersion() 
    {
        UnityWebRequest www = UnityWebRequest.Get("https://blackrocket.com/files/battle-royale-version.json");

	    if (!m_requireCert)
        {
            var cert = new ForceAcceptAll();
            www.certificateHandler = cert;
        }
        
	    www.SendWebRequest();

        while (!www.isDone)
            yield return null;

	    GameVersion serverVersion = JsonUtility.FromJson<GameVersion>(www.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(loginCanvas);

            yield break;
        }

        // 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(loginCanvas);
            yield break;
        }
        #endregion

        // HANDLE NEW VERSION CONVENTIONS //
        #region
	    string dateTimeString = serverVersion.version;
	    string[] serverSubstrings = dateTimeString.Split('_');
	    string[] clientSubstrings = _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(oldVersionCanvas);
		    yield break;
	    }
	    
	    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(oldVersionCanvas);
		    	yield break;
		    }
		    
	    if (m_debugChannel)
		    m_debugChannel.Raise(this, 
		    new string[]{
			    "Client version validated!",
			    "Server version: " + dateTimeString + " | Client version: " + _clientVersion}
		    );
		    
	    SetActiveCanvas(loginCanvas);
        #endregion

        //double currentVersionDouble = currentVersion != null ? Convert.ToDouble(currentVersion.version) : Convert.ToDouble(editorVersion);

        //if (m_debugChannel)
        //    m_debugChannel.Raise(this, new string[]{
        //    "Web request complete!",
        //    "Server version " + serverVersionDouble + " : Client version " + editorVersionDouble});

        //if (serverVersionDouble > editorVersionDouble)
        //    SetActiveCanvas(oldVersionCanvas);
        //else
        //    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;
}
