// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMAArchive
    {
        private const string DefaultBaseUrl = "https://reqid.io";

        private const string RetiredBaseUrl = "https://reqid.io/wmpfa";

        private const string AllowedHost = "reqid.io";

        private static readonly TimeSpan OfflineGrace = TimeSpan.FromDays(7);

        private const string BaseUrlKey = "WPFMA.Archive.BaseUrl";
        private const string TokenKey = "WPFMA.Archive.Token";
        private const string ExpiryKey = "WPFMA.Archive.ExpiresAt";
        private const string LabelKey = "WPFMA.Archive.Label";
        private const string FilesKey = "WPFMA.Archive.Files";
        private const string StatusKey = "WPFMA.Archive.Status";
        private const string LastCheckKey = "WPFMA.Archive.LastCheck";
        private const string NonceKey = "WPFMA.Archive.Nonce";

        private static readonly TimeSpan CheckInterval = TimeSpan.FromHours(6);

        static WPFMAArchive()
        {
            EditorApplication.delayCall += () =>
            {
                if (HasToken)
                    Check(false);
            };
        }

        internal static string BaseUrl
        {
            get
            {
                string stored = EditorPrefs.GetString(BaseUrlKey, DefaultBaseUrl);
                if (string.IsNullOrWhiteSpace(stored) ||
                    string.Equals(stored.TrimEnd('/'), RetiredBaseUrl, StringComparison.OrdinalIgnoreCase))
                    return DefaultBaseUrl;

                return stored.TrimEnd('/');
            }
            set
            {
                string wanted = (value ?? string.Empty).Trim().TrimEnd('/');
                if (wanted.Length > 0 && !IsAllowed(wanted))
                {
                    Debug.LogWarning("[WPFMA-SDK] '" + wanted + "' was not accepted: the archive is only read over " +
                                     "https from " + AllowedHost + ".");
                    return;
                }

                EditorPrefs.SetString(BaseUrlKey, wanted);
            }
        }

        internal static string Token
        {
            get { return Unmask(EditorPrefs.GetString(TokenKey, string.Empty)); }
            private set { EditorPrefs.SetString(TokenKey, Mask(value ?? string.Empty)); }
        }

        private static string Mask(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;

            var bytes = System.Text.Encoding.UTF8.GetBytes(value);
            var key = System.Text.Encoding.UTF8.GetBytes(SystemInfo.deviceUniqueIdentifier + "wmpfa");
            for (int i = 0; i < bytes.Length; i++)
                bytes[i] ^= key[i % key.Length];

            return Convert.ToBase64String(bytes);
        }

        private static string Unmask(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;

            try
            {
                var bytes = Convert.FromBase64String(value);
                var key = System.Text.Encoding.UTF8.GetBytes(SystemInfo.deviceUniqueIdentifier + "wmpfa");
                for (int i = 0; i < bytes.Length; i++)
                    bytes[i] ^= key[i % key.Length];

                return System.Text.Encoding.UTF8.GetString(bytes);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        internal static bool HasToken => !string.IsNullOrEmpty(Token);

        internal static bool IsUnlocked => HasToken;

        internal static string Label => EditorPrefs.GetString(LabelKey, string.Empty);

        internal static int Files => EditorPrefs.GetInt(FilesKey, 0);

        internal static string Status
        {
            get { return EditorPrefs.GetString(StatusKey, "No access code redeemed."); }
            private set { EditorPrefs.SetString(StatusKey, value ?? string.Empty); }
        }

        internal static DateTime ExpiresAt
        {
            get
            {
                long stamp = Convert.ToInt64(EditorPrefs.GetString(ExpiryKey, "0"));
                return stamp <= 0 ? DateTime.MinValue : Epoch.AddSeconds(stamp);
            }
        }

        private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        private static bool IsAllowed(string url)
        {
            Uri parsed;
            if (!Uri.TryCreate(url, UriKind.Absolute, out parsed))
                return false;

            if (parsed.Scheme != Uri.UriSchemeHttps)
                return false;

            string host = parsed.Host;
            return string.Equals(host, AllowedHost, StringComparison.OrdinalIgnoreCase) ||
                   host.EndsWith("." + AllowedHost, StringComparison.OrdinalIgnoreCase);
        }

        private static string MachineId => SystemInfo.deviceUniqueIdentifier;

        internal static bool Ping(out string message)
        {
            string body;
            long status;
            if (!Send(UnityWebRequest.kHttpVerbGET, "/api/ping.php", null, false, out body, out status, out message))
                return false;

            message = "Server reachable.";
            return true;
        }

        internal static bool Redeem(string code, out string message)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                message = "Enter your access code first.";
                return false;
            }

            var form = new WWWForm();
            form.AddField("code", code.Trim());
            form.AddField("machine_id", MachineId);
            form.AddField("label", Application.productName + " on " + Environment.MachineName);

            string body;
            long status;
            if (!Send(UnityWebRequest.kHttpVerbPOST, "/api/verify.php", form, false, out body, out status, out message))
            {
                Status = message;
                return false;
            }

            VerifyResponse response;
            if (!TryParse(body, out response, out message))
            {
                Status = message;
                return false;
            }

            if (response == null || !response.ok || string.IsNullOrEmpty(response.token))
            {
                message = Describe(response != null ? response.error : null,
                    response != null ? response.message : null, "That code was not accepted.");
                Status = message;
                return false;
            }

            Token = response.token;
            EditorPrefs.SetString(ExpiryKey, response.expires_at.ToString());
            EditorPrefs.SetInt(FilesKey, response.files);
            EditorPrefs.SetString(LastCheckKey, DateTime.UtcNow.Ticks.ToString());
            Status = "Unlocked. " + response.files + " file(s) in the archive.";
            message = string.IsNullOrEmpty(response.message) ? Status : response.message;
            return true;
        }

        internal static bool Check(bool force)
        {
            if (!HasToken)
                return false;

            if (!force)
            {
                long ticks;
                if (long.TryParse(EditorPrefs.GetString(LastCheckKey, "0"), out ticks) && ticks > 0 &&
                    DateTime.UtcNow - new DateTime(ticks, DateTimeKind.Utc) < CheckInterval)
                    return true;
            }

            string body, message;
            long status;
            string nonce = Guid.NewGuid().ToString("N");
            SessionState.SetString(NonceKey, nonce);

            if (!Send(UnityWebRequest.kHttpVerbGET, "/api/check.php?machine_id=" + UnityWebRequest.EscapeURL(MachineId) +
                        "&nonce=" + nonce,
                    null, true, out body, out status, out message))
            {
                if (status == 0)
                {
                    var since = LastGoodCheck();
                    if (since != DateTime.MinValue && DateTime.UtcNow - since > OfflineGrace)
                    {
                        Clear("Locked: the server has not confirmed this session in " +
                              (int)OfflineGrace.TotalDays + " days.");
                        return false;
                    }

                    Status = "Unlocked, but the server could not be reached to re-check.";
                    return true;
                }

                Clear(message);
                return false;
            }

            CheckResponse response;
            if (!TryParse(body, out response, out message))
            {
                Status = "Unlocked, but the server's reply could not be read.";
                return true;
            }

            if (response != null && !string.IsNullOrEmpty(response.nonce) &&
                response.nonce != SessionState.GetString(NonceKey, string.Empty))
            {
                Debug.LogWarning("[WPFMA-SDK] The archive's reply did not match the request it was for; ignoring it.");
                Status = "Unlocked, but the last reply from the server could not be trusted.";
                return true;
            }

            if (response == null || !response.ok || !response.valid)
            {
                Clear(Describe(response != null ? response.error : null,
                    response != null ? response.message : null, "The access code is no longer valid."));
                return false;
            }

            EditorPrefs.SetString(ExpiryKey, response.expires_at.ToString());
            EditorPrefs.SetInt(FilesKey, response.files);
            EditorPrefs.SetString(LabelKey, response.label ?? string.Empty);
            EditorPrefs.SetString(LastCheckKey, DateTime.UtcNow.Ticks.ToString());
            Status = "Unlocked" + (string.IsNullOrEmpty(response.label) ? "" : " as '" + response.label + "'") +
                     ". " + response.files + " file(s) in the archive.";
            return true;
        }

        internal static List<CatalogEntry> Catalog(out string message)
        {
            var all = new List<CatalogEntry>();
            message = null;

            if (!IsUnlocked)
            {
                message = "Redeem an access code first.";
                return all;
            }

            string body;
            long status;
            if (!Send(UnityWebRequest.kHttpVerbGET, "/api/catalog.php?per_page=0", null, true,
                    out body, out status, out message))
                return all;

            CatalogResponse response;
            if (!TryParse(body, out response, out message))
                return all;

            if (response == null || !response.ok)
            {
                message = Describe(response != null ? response.error : null,
                    response != null ? response.message : null, "The catalog could not be read.");
                return all;
            }

            if (response.entries != null)
                all.AddRange(response.entries);

            return all;
        }

        internal static string Download(CatalogEntry entry, string folder, out string message)
        {
            message = null;
            if (entry == null || string.IsNullOrEmpty(entry.id))
            {
                message = "That catalog entry has no id.";
                return null;
            }

            if (!IsUnlocked)
            {
                message = "Redeem an access code first.";
                return null;
            }

            Directory.CreateDirectory(folder);
            string destination = Path.Combine(folder, SafeFileName(entry.file ?? entry.title ?? entry.id));

            using (var request = UnityWebRequest.Get(BaseUrl + "/api/download.php?id=" + UnityWebRequest.EscapeURL(entry.id)))
            {
                Authorise(request);
                var handler = new DownloadHandlerFile(destination) { removeFileOnAbort = true };
                request.downloadHandler = handler;

                var operation = request.SendWebRequest();
                try
                {
                    while (!operation.isDone)
                    {
                        if (EditorUtility.DisplayCancelableProgressBar("WPFMA-SDK",
                                "Downloading " + (entry.title ?? entry.file), request.downloadProgress))
                        {
                            request.Abort();
                            message = "Download cancelled.";
                            return null;
                        }
                    }
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                }

                if (request.result != UnityWebRequest.Result.Success)
                {
                    message = "Download failed: " + request.error;
                    return null;
                }
            }

            return destination;
        }

        private static bool Send(string verb, string path, WWWForm form, bool authorise,
            out string body, out long status, out string message)
        {
            body = null;
            status = 0;
            message = null;

            using (var request = form != null
                       ? UnityWebRequest.Post(BaseUrl + path, form)
                       : new UnityWebRequest(BaseUrl + path, verb) { downloadHandler = new DownloadHandlerBuffer() })
            {
                if (authorise)
                    Authorise(request);

                request.timeout = 20;

                var operation = request.SendWebRequest();
                while (!operation.isDone)
                {
                }

                status = request.responseCode;
                body = request.downloadHandler != null ? request.downloadHandler.text : null;

                if (request.result == UnityWebRequest.Result.ConnectionError)
                {
                    message = "Could not reach " + BaseUrl + ": " + request.error;
                    status = 0;
                    return false;
                }

                if (string.IsNullOrEmpty(body))
                {
                    message = "The server returned nothing (HTTP " + status + ").";
                    return false;
                }

                if (status >= 400)
                {
                    ErrorResponse failure;
                    string parseError;
                    if (!TryParse(body, out failure, out parseError))
                    {
                        message = "HTTP " + status + ". " + parseError;
                        return false;
                    }

                    message = Describe(failure != null ? failure.error : null,
                        failure != null ? failure.message : null, "HTTP " + status + ".");
                    return false;
                }

                return true;
            }
        }

        private static bool TryParse<T>(string body, out T result, out string error) where T : class
        {
            result = null;
            error = null;

            if (string.IsNullOrEmpty(body))
            {
                error = "The server returned an empty reply.";
                return false;
            }

            try
            {
                result = JsonUtility.FromJson<T>(body);
                if (result != null)
                    return true;
            }
            catch (Exception)
            {
            }

            int start = body.IndexOf('{');
            int end = body.LastIndexOf('}');
            if (start >= 0 && end > start)
            {
                try
                {
                    result = JsonUtility.FromJson<T>(body.Substring(start, end - start + 1));
                    if (result != null)
                    {
                        Debug.LogWarning("[WPFMA-SDK] The archive server sent something before its JSON: " +
                                         Snippet(body.Substring(0, start)));
                        return true;
                    }
                }
                catch (Exception)
                {
                }
            }

            error = "The server did not return JSON. It said: " + Snippet(body);
            Debug.LogWarning("[WPFMA-SDK] Unreadable reply from " + BaseUrl + ":" + Environment.NewLine + Snippet(body, 800));
            return false;
        }

        private static string Snippet(string text, int length = 200)
        {
            if (string.IsNullOrEmpty(text))
                return "(nothing)";

            text = text.Replace('\r', ' ').Replace('\n', ' ').Trim();
            return text.Length <= length ? text : text.Substring(0, length) + "...";
        }

        private static void Authorise(UnityWebRequest request)
        {
            string token = Token;
            if (string.IsNullOrEmpty(token))
                return;

            request.SetRequestHeader("Authorization", "Bearer " + token);

            request.SetRequestHeader("X-Wmpfa-Token", token);
        }

        private static DateTime LastGoodCheck()
        {
            long ticks;
            if (!long.TryParse(EditorPrefs.GetString(LastCheckKey, "0"), out ticks) || ticks <= 0)
                return DateTime.MinValue;

            return new DateTime(ticks, DateTimeKind.Utc);
        }

        internal static void Clear(string reason)
        {
            Token = string.Empty;
            EditorPrefs.SetString(ExpiryKey, "0");
            EditorPrefs.SetInt(FilesKey, 0);
            EditorPrefs.SetString(LabelKey, string.Empty);
            EditorPrefs.SetString(LastCheckKey, "0");
            Status = string.IsNullOrEmpty(reason) ? "Locked." : reason;
        }

        private static string Describe(string slug, string serverMessage, string fallback)
        {
            if (!string.IsNullOrEmpty(serverMessage))
                return serverMessage;

            switch (slug)
            {
                case "code_invalid": return "That access code is not recognised.";
                case "code_revoked": return "That access code has been revoked.";
                case "code_expired": return "That access code has expired.";
                case "code_exhausted": return "That access code has been used too many times.";
                case "rate_limited": return "Too many attempts. Wait a few minutes and try again.";
                case "token_invalid":
                case "token_expired":
                case "token_revoked": return "The saved session is no longer valid. Redeem your code again.";
                case "machine_mismatch": return "That code is bound to a different machine.";
                case "file_not_found": return "That file is no longer in the archive.";
                case "server_misconfigured": return "The server reports it is not fully configured.";
                default: return fallback;
            }
        }

        private static string SafeFileName(string name)
        {
            return WPFMAPaths.SafeFileName(name);
        }

        [Serializable]
        private sealed class ErrorResponse
        {
            public bool ok;
            public string error;
            public string message;
        }

        [Serializable]
        private sealed class VerifyResponse
        {
            public bool ok;
            public string token;
            public long expires_at;
            public int files;
            public string message;
            public string error;
        }

        [Serializable]
        private sealed class CheckResponse
        {
            public bool ok;
            public bool valid;
            public long expires_at;
            public int files;
            public string label;
            public string nonce;
            public string message;
            public string error;
        }

        [Serializable]
        private sealed class CatalogResponse
        {
            public bool ok;
            public int total;
            public int count;
            public int page;
            public int pages;
            public string[] collections;
            public CatalogEntry[] entries;
            public string message;
            public string error;
        }

        [Serializable]
        internal sealed class CatalogEntry
        {
            public string id;
            public string title;
            public string file;
            public string collection;
            public string ext;
            public long size;
            public string size_human;
            public string author;
            public string version;
            public string description;
            public string[] tags;
            public string download_url;
        }
    }
}
#endif
