// 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.Diagnostics;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace WPFMA
{
    public static class WPFMAReUploadSection
    {
        private const string SectionTitle = "Re-upload";
        private const string VrcaPrefKey = "WPFMA.ReUpload.LastVrca";
        private const string ImagePrefKey = "WPFMA.ReUpload.LastImage";
        private const string ConfirmPrefKey = "WPFMA.ReUpload.Confirm";

        private const float PreferredAspect = 4f / 3f;

        private const int MaxOutputChars = 16000;

        private static Color AccentBlue => WPFMATheme.Shift(new Color(126f / 255f, 182f / 255f, 222f / 255f));

        private static Color AccentText => WPFMATheme.Shift(new Color(14f / 255f, 24f / 255f, 33f / 255f));

        private static Color ToolbarBackground => WPFMATheme.Shift(new Color(24f / 255f, 29f / 255f, 37f / 255f));

        private static Color ToolbarEdge => WPFMATheme.Shift(new Color(11f / 255f, 14f / 255f, 18f / 255f));

        private static Color FaintText => WPFMATheme.Shift(new Color(78f / 255f, 91f / 255f, 105f / 255f));

        private static bool initialised;
        private static string vrcaPath = string.Empty;
        private static string imagePath = string.Empty;
        private static string avatarName = string.Empty;
        private static bool confirmBeforeUpload = true;
        private static bool sessionExpanded;

        private static string vrcaInfo;
        private static string vrcaProblem;
        private static string imageInfo;
        private static string imageProblem;

        private static GUIStyle accentButtonStyle;
        private static int stylesTheme = -1;
        private static Process running;
        private static string[] lastArguments;
        private static string lastDescription;
        private static bool lastUnattended;
        private static bool retriedWithoutGpu;
        private static readonly StringBuilder Output = new StringBuilder();
        private static bool outputTruncated;
        private static string lastResult;

        public static void Draw(GUIStyle sectionStyle, GUIStyle titleStyle, GUIStyle pathStyle)
        {
            Initialise();
            EnsureVisualStyles();

            EditorGUILayout.Space(10f);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(sectionStyle);

            if (!DrawSectionStrip(SectionTitle, "external tool"))
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
                return;
            }

            DrawSubtitle("Publish a .vrca through the external re-upload tool");

            if (!DrawTool(pathStyle))
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
                return;
            }

            EditorGUILayout.Space(8f);
            DrawInputs(pathStyle);
            EditorGUILayout.Space(8f);
            DrawUpload();
            DrawOutput(pathStyle);

            EditorGUILayout.EndVertical();
            GUILayout.Space(8f);
            EditorGUILayout.EndHorizontal();
        }

        private const string ExpandedPrefKey = "WPFMA.Tools.ReUploadExpanded";

        private static bool DrawSectionStrip(string title, string detail)
        {
            bool expanded = EditorPrefs.GetBool(ExpandedPrefKey, true);

            var rect = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), ToolbarEdge);

            GUI.Label(new Rect(rect.x + 8f, rect.y, 14f, rect.height), expanded ? "\u25be" : "\u25b8",
                new GUIStyle(EditorStyles.label) { fontSize = 12, normal = { textColor = AccentBlue } });

            GUI.Label(new Rect(rect.x + 24f, rect.y, 240f, rect.height), title,
                new GUIStyle(EditorStyles.label) { fontSize = 12, normal = { textColor = AccentBlue } });

            GUI.Label(new Rect(rect.xMax - 204f, rect.y, 200f, rect.height), detail,
                new GUIStyle(EditorStyles.label)
                {
                    fontSize = 11,
                    alignment = TextAnchor.MiddleRight,
                    normal = { textColor = FaintText }
                });

            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);

            var evt = Event.current;
            if (evt.type == EventType.MouseDown && evt.button == 0 && rect.Contains(evt.mousePosition))
            {
                expanded = !expanded;
                EditorPrefs.SetBool(ExpandedPrefKey, expanded);
                evt.Use();
            }

            return expanded;
        }

        private static void DrawSubtitle(string text)
        {
            var rect = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
            GUI.Label(new Rect(rect.x + 8f, rect.y, rect.width - 16f, rect.height), text,
                new GUIStyle(EditorStyles.label) { fontSize = 11, normal = { textColor = FaintText } });
        }

        private static void Initialise()
        {
            if (initialised)
                return;

            initialised = true;
            vrcaPath = EditorPrefs.GetString(VrcaPrefKey, string.Empty);
            imagePath = EditorPrefs.GetString(ImagePrefKey, string.Empty);
            confirmBeforeUpload = EditorPrefs.GetBool(ConfirmPrefKey, true);
            InspectVrca();
            InspectImage();
        }

        private static bool DrawTool(GUIStyle pathStyle)
        {
            if (!Vrca.WPFMAReUpload.IsConfigured)
            {
                EditorGUILayout.HelpBox(
                    Application.platform == RuntimePlatform.WindowsEditor
                        ? "The re-upload tool could not be found. Point at its .exe to continue."
                        : "The re-upload tool could not be found. Point at the native build, or at the .exe to " +
                          "run it through Wine.",
                    MessageType.Error);

                if (DrawButton("Locate tool", 24f))
                    Vrca.WPFMAReUpload.Locate();

                return false;
            }

            EditorGUILayout.LabelField(
                Vrca.WPFMAReUpload.UsesOverride ? Vrca.WPFMAReUpload.ToolPath : "Tool: bundled with the SDK",
                pathStyle);

            if (Vrca.WPFMAReUpload.RunsThroughWine(Vrca.WPFMAReUpload.ToolPath))
            {
                string wine = Vrca.WPFMAReUpload.Wine;
                EditorGUILayout.HelpBox(
                    wine == null
                        ? "This is the Windows build and there is no Wine on this system to run it with. " +
                          "Install Wine, or point at a native build."
                        : "Windows build, running through Wine (" + wine + "). Wine prints harmless notes about " +
                          "unimplemented calls; those are not errors.",
                    wine == null ? MessageType.Warning : MessageType.Info);
            }

            if (GUILayout.Button("Session", tabStyle, GUILayout.Height(24f)))
                sessionExpanded = !sessionExpanded;

            if (!sessionExpanded)
                return true;

            EditorGUILayout.HelpBox(
                "Sign in once with the tool — it keeps its own session afterwards and uploads reuse it. " +
                "WPFMA-SDK never sees your credentials and stores nothing.",
                MessageType.Info);

            using (new EditorGUILayout.HorizontalScope())
            {
                if (DrawButton("Sign in", 22f))
                    RunTool(null, "opening the tool");

                if (DrawButton("Force login", 22f))
                    RunTool(new[] { "--force-login" }, "forcing a new login");

                if (DrawButton("Clear session", 22f))
                {
                    if (EditorUtility.DisplayDialog(SectionTitle,
                            "Delete the tool's saved session and cookies?\n\nYou will need to sign in again.",
                            "Clear", "Cancel"))
                        RunTool(new[] { "--clear" }, "clearing the saved session");
                }
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                if (DrawButton(Vrca.WPFMAReUpload.UsesOverride ? "Change tool" : "Use another tool", 20f))
                    Vrca.WPFMAReUpload.Locate();

                if (Vrca.WPFMAReUpload.UsesOverride && DrawButton("Reset", 20f, GUILayout.Width(70f)))
                    Vrca.WPFMAReUpload.ClearOverride();
            }

            return true;
        }

        private static void DrawInputs(GUIStyle pathStyle)
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                string edited = EditorGUILayout.TextField("Bundle", vrcaPath);
                if (edited != vrcaPath)
                {
                    vrcaPath = edited;
                    InspectVrca();
                }

                if (DrawButton("Browse", 18f, GUILayout.Width(70f)))
                {
                    string picked = EditorUtility.OpenFilePanel("Select the .vrca to upload", string.Empty, "vrca");
                    if (!string.IsNullOrEmpty(picked))
                    {
                        vrcaPath = picked;
                        EditorPrefs.SetString(VrcaPrefKey, vrcaPath);
                        InspectVrca();
                    }
                }

                string previewed = Vrca.WPFMAVrcaPreview.GetFirstLoadedPath();
                using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(previewed)))
                {
                    if (DrawButton("From preview", 18f, GUILayout.Width(100f)))
                    {
                        vrcaPath = previewed;
                        EditorPrefs.SetString(VrcaPrefKey, vrcaPath);
                        InspectVrca();
                    }
                }
            }

            if (!string.IsNullOrEmpty(vrcaProblem))
                EditorGUILayout.HelpBox(vrcaProblem, MessageType.Error);
            else if (!string.IsNullOrEmpty(vrcaInfo))
                EditorGUILayout.LabelField(vrcaInfo, pathStyle);

            EditorGUILayout.Space(4f);

            using (new EditorGUILayout.HorizontalScope())
            {
                string edited = EditorGUILayout.TextField("Thumbnail", imagePath);
                if (edited != imagePath)
                {
                    imagePath = edited;
                    InspectImage();
                }

                if (DrawButton("Browse", 18f, GUILayout.Width(70f)))
                {
                    string picked = EditorUtility.OpenFilePanel("Select a thumbnail", string.Empty, "png,jpg,jpeg");
                    if (!string.IsNullOrEmpty(picked))
                    {
                        imagePath = picked;
                        EditorPrefs.SetString(ImagePrefKey, imagePath);
                        InspectImage();
                    }
                }
            }

            if (!string.IsNullOrEmpty(imageProblem))
                EditorGUILayout.HelpBox(imageProblem, MessageType.Warning);
            else if (!string.IsNullOrEmpty(imageInfo))
                EditorGUILayout.LabelField(imageInfo, pathStyle);

            EditorGUILayout.Space(4f);
            avatarName = EditorGUILayout.TextField("Name", avatarName);
        }

        private static void InspectVrca()
        {
            vrcaInfo = null;
            vrcaProblem = null;

            if (string.IsNullOrEmpty(vrcaPath))
                return;

            if (!File.Exists(vrcaPath))
            {
                vrcaProblem = "That file does not exist.";
                return;
            }

            try
            {
                using (var stream = File.OpenRead(vrcaPath))
                {
                    var bundle = Vrca.WPFMAVrcaBundle.Open(stream);

                    if (bundle.UsesContentEncryption)
                    {
                        vrcaProblem = "This bundle is encrypted, so its contents cannot be read or re-uploaded.";
                        return;
                    }

                    vrcaInfo = "UnityFS v" + bundle.FormatVersion + "  |  Unity " + bundle.UnityRevision +
                               "  |  " + bundle.Nodes.Count + " file(s)  |  " +
                               (new FileInfo(vrcaPath).Length / (1024f * 1024f)).ToString("F1") + " MB";
                }
            }
            catch (Exception e)
            {
                vrcaProblem = "Not a readable .vrca: " + e.Message;
            }
        }

        private static void InspectImage()
        {
            imageInfo = null;
            imageProblem = null;

            if (string.IsNullOrEmpty(imagePath))
                return;

            if (!File.Exists(imagePath))
            {
                imageProblem = "That image does not exist.";
                return;
            }

            string extension = Path.GetExtension(imagePath).ToLowerInvariant();
            if (extension != ".png" && extension != ".jpg" && extension != ".jpeg")
            {
                imageProblem = "The thumbnail should be a .png or .jpg.";
                return;
            }

            var texture = new Texture2D(2, 2);
            try
            {
                if (!texture.LoadImage(File.ReadAllBytes(imagePath)))
                {
                    imageProblem = "That image could not be read.";
                    return;
                }

                float aspect = (float)texture.width / texture.height;
                imageInfo = texture.width + "x" + texture.height + "  (" + aspect.ToString("F2") + ":1)";

                if (Mathf.Abs(aspect - PreferredAspect) > 0.05f)
                    imageProblem = imageInfo + " — VRChat displays thumbnails at 4:3 (1200x900), so this will be cropped.";
            }
            catch (Exception e)
            {
                imageProblem = "That image could not be read: " + e.Message;
            }
            finally
            {
                UnityEngine.Object.DestroyImmediate(texture);
            }
        }

        private static void DrawUpload()
        {
            bool confirm = EditorGUILayout.ToggleLeft("Ask before uploading", confirmBeforeUpload);
            if (confirm != confirmBeforeUpload)
            {
                confirmBeforeUpload = confirm;
                EditorPrefs.SetBool(ConfirmPrefKey, confirm);
            }

            bool ready = string.IsNullOrEmpty(vrcaProblem) && !string.IsNullOrEmpty(vrcaPath)
                         && !string.IsNullOrEmpty(imagePath) && File.Exists(imagePath)
                         && !string.IsNullOrEmpty(avatarName.Trim())
                         && running == null;

            using (new EditorGUILayout.HorizontalScope())
            {
                using (new EditorGUI.DisabledScope(!ready))
                {
                    if (DrawButton(running != null ? "Uploading…" : "Upload", 28f))
                        Upload();
                }

                if (running != null && DrawButton("Stop", 28f, GUILayout.Width(80f)))
                    StopRunning();
            }

            if (running == null && !ready)
                EditorGUILayout.LabelField("Set a readable bundle, a thumbnail and a name to enable uploading.",
                    EditorStyles.miniLabel);

            EditorGUILayout.HelpBox(
                "Uploading publishes under whichever account the tool is signed into. Only do this with avatars you " +
                "made — re-uploading someone else's work is not yours to publish, and it is that account which " +
                "carries the consequences.",
                MessageType.None);
        }

        private static void Upload()
        {
            if (confirmBeforeUpload && !EditorUtility.DisplayDialog(SectionTitle,
                    "Upload this avatar?\n\n" +
                    "Name:  " + avatarName.Trim() + "\n" +
                    "Bundle:  " + Path.GetFileName(vrcaPath) + "\n" +
                    "Thumbnail:  " + Path.GetFileName(imagePath) + "\n\n" +
                    "It will be published under the account the tool is signed into.",
                    "Upload", "Cancel"))
                return;

            EditorPrefs.SetString(VrcaPrefKey, vrcaPath);
            EditorPrefs.SetString(ImagePrefKey, imagePath);

            RunTool(new[]
            {
                "--cli",
                "--vrca", vrcaPath,
                "--image", imagePath,
                "--name", avatarName.Trim()
            }, "uploading " + avatarName.Trim());
        }

        private static void RunTool(string[] arguments, string description)
        {
            if (running != null)
                return;

            if (!Vrca.WPFMAReUpload.IsConfigured)
            {
                EditorUtility.DisplayDialog(SectionTitle, "The re-upload tool could not be found.", "OK");
                return;
            }

            string tool = Vrca.WPFMAReUpload.ToolPath;

            lock (Output)
                Output.Length = 0;
            outputTruncated = false;
            lastResult = null;

            bool unattended = arguments != null && Array.IndexOf(arguments, "--cli") >= 0;

            lastArguments = arguments;
            lastDescription = description;

            lastUnattended = unattended;
            bool linux = Application.platform == RuntimePlatform.LinuxEditor;

            bool wine = Vrca.WPFMAReUpload.RunsThroughWine(tool);
            bool capture = unattended || linux || wine;

            var info = new ProcessStartInfo
            {
                UseShellExecute = !capture,
                CreateNoWindow = unattended,
                RedirectStandardOutput = capture,
                RedirectStandardError = capture
            };

            if (!Vrca.WPFMAReUpload.ConfigureStart(info, tool))
                return;

            if (linux && (retriedWithoutGpu || Vrca.WPFMAReUpload.ForceSoftwareRendering))
            {
                info.Environment["LIBGL_ALWAYS_SOFTWARE"] = "1";
                info.Environment["GALLIUM_DRIVER"] = "llvmpipe";
                info.Environment["ELECTRON_DISABLE_GPU"] = "1";
            }

            if (arguments != null)
                foreach (var argument in arguments)
                    info.ArgumentList.Add(argument);

            try
            {
                running = new Process { StartInfo = info, EnableRaisingEvents = true };

                if (capture)
                {
                    running.OutputDataReceived += (s, e) => AppendOutput(e.Data);
                    running.ErrorDataReceived += (s, e) => AppendOutput(e.Data);
                }

                running.Start();

                if (capture)
                {
                    running.BeginOutputReadLine();
                    running.BeginErrorReadLine();
                }

                Debug.Log("[WPFMA-SDK] Re-upload tool: " + description + "…");
                EditorApplication.update += PollProcess;
            }
            catch (Exception e)
            {
                running = null;
                lastResult = "Could not start the tool: " + e.Message;
                Debug.LogError("[WPFMA-SDK] " + lastResult);
            }
        }

        private static bool LooksLikeGraphicsFailure()
        {
            string text;
            lock (Output)
                text = Output.ToString();

            if (string.IsNullOrEmpty(text))
                return false;

            return text.IndexOf("dri2 screen", StringComparison.OrdinalIgnoreCase) >= 0 ||
                   text.IndexOf("MESA-EGL", StringComparison.OrdinalIgnoreCase) >= 0 ||
                   text.IndexOf("failed to create", StringComparison.OrdinalIgnoreCase) >= 0 &&
                   text.IndexOf("egl", StringComparison.OrdinalIgnoreCase) >= 0;
        }

        private static void AppendOutput(string line)
        {
            if (line == null)
                return;

            lock (Output)
            {
                if (Output.Length >= MaxOutputChars)
                {
                    outputTruncated = true;
                    return;
                }

                Output.AppendLine(line);
            }
        }

        private static void StopRunning()
        {
            if (running == null)
                return;

            try
            {
                if (!running.HasExited)
                    running.Kill();
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not stop the re-upload tool: " + e.Message);
            }
            finally
            {
                EditorApplication.update -= PollProcess;
                running.Dispose();
                running = null;
                lastResult = "Stopped.";
            }
        }

        private static void PollProcess()
        {
            if (running == null)
            {
                EditorApplication.update -= PollProcess;
                return;
            }

            if (!running.HasExited)
                return;

            EditorApplication.update -= PollProcess;

            int code = running.ExitCode;
            running.Dispose();
            running = null;

            if (code == 0)
            {
                retriedWithoutGpu = false;
                lastResult = "Finished successfully.";
                Debug.Log("[WPFMA-SDK] Re-upload tool finished.");
                return;
            }

            if (!retriedWithoutGpu && LooksLikeGraphicsFailure())
            {
                retriedWithoutGpu = true;
                lastResult = "The tool could not use the GPU; trying again with software rendering.";
                Debug.LogWarning("[WPFMA-SDK] " + lastResult);
                RunTool(lastArguments, lastDescription);
                return;
            }

            lastResult = "The tool exited with code " + code + "." +
                         (retriedWithoutGpu ? " Software rendering did not help either." : string.Empty);
            Debug.LogWarning("[WPFMA-SDK] Re-upload tool exited with code " + code +
                             ". See the output in Tools > Re-upload.");
            retriedWithoutGpu = false;
        }

        private static void DrawOutput(GUIStyle pathStyle)
        {
            string text;
            lock (Output)
                text = Output.ToString();

            if (string.IsNullOrEmpty(lastResult) && string.IsNullOrEmpty(text))
                return;

            EditorGUILayout.Space(6f);

            if (!string.IsNullOrEmpty(lastResult))
                EditorGUILayout.LabelField(lastResult, pathStyle);

            if (!string.IsNullOrEmpty(text))
            {
                if (text.Length > MaxOutputChars)
                    text = text.Substring(text.Length - MaxOutputChars);

                EditorGUILayout.TextArea(text, GUILayout.MinHeight(90f), GUILayout.MaxHeight(200f));

                if (outputTruncated)
                    EditorGUILayout.LabelField("Output truncated — see ubzig.log for the full run.", pathStyle);
            }

            string log = Path.Combine(Path.GetDirectoryName(Vrca.WPFMAReUpload.ToolPath), "ubzig.log");
            if (File.Exists(log) && DrawButton("Open ubzig.log", 20f))
                EditorUtility.RevealInFinder(log);
        }

        private static GUIStyle tabStyle;

        private static void EnsureVisualStyles()
        {
            if (accentButtonStyle != null && accentButtonStyle.normal.background != null && stylesTheme == WPFMATheme.Version)
                return;

            accentButtonStyle = Flat(AccentBlue, AccentText);
            tabStyle = Flat(WPFMATheme.Shift(new Color(33f / 255f, 38f / 255f, 46f / 255f)), new Color(0.85f, 0.85f, 0.85f));
            stylesTheme = WPFMATheme.Version;
        }

        private static GUIStyle Flat(Color color, Color textColor)
        {
            var texture = new Texture2D(1, 1);
            texture.SetPixel(0, 0, color);
            texture.Apply();
            texture.hideFlags = HideFlags.HideAndDontSave;

            return new GUIStyle(GUI.skin.button)
            {
                normal = { background = texture, textColor = textColor },
                hover = { background = texture, textColor = textColor },
                active = { background = texture, textColor = textColor },
                focused = { background = texture, textColor = textColor }
            };
        }

        private static bool DrawButton(string label, float height, params GUILayoutOption[] options)
        {
            var layout = new GUILayoutOption[options.Length + 1];
            layout[0] = GUILayout.Height(height);
            options.CopyTo(layout, 1);
            return GUILayout.Button(label, accentButtonStyle, layout);
        }
    }
}
#endif
