// 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 System.Linq;
using UnityEditor;
using UnityEngine;
using WPFMA.Vrca;

namespace WPFMA
{
    internal static class WPFMABuildSizeExplorer
    {
        internal sealed class Item
        {
            public string Name;
            public string Kind;
            public long Bytes;
        }

        internal sealed class Report
        {
            public string Path;
            public long FileBytes;
            public long ContentBytes;
            public readonly List<Item> Items = new List<Item>();
            public readonly Dictionary<string, long> ByKind = new Dictionary<string, long>();
        }

        private static readonly Dictionary<int, string> Kinds = new Dictionary<int, string>
        {
            { 21, "Material" }, { 28, "Texture" }, { 43, "Mesh" }, { 48, "Shader" }, { 74, "Animation" },
            { 83, "Audio" }, { 89, "Cubemap" }, { 91, "Animator" }, { 114, "Script data" }, { 117, "Texture3D" },
            { 128, "Font" }, { 187, "Texture array" }, { 213, "Sprite" }, { 1, "GameObject" }, { 4, "Transform" },
            { 23, "Mesh renderer" }, { 137, "Skinned renderer" }
        };

        internal static string LastBuildPath()
        {
            string path = UnityEngine.Networking.UnityWebRequest.UnEscapeURL(EditorPrefs.GetString("lastVRCPath", string.Empty));
            if (path.StartsWith("file:///"))
                path = path.Substring("file:///".Length);
            return !string.IsNullOrEmpty(path) && File.Exists(path) ? path : null;
        }

        internal static Report Read(string path)
        {
            var report = new Report { Path = path, FileBytes = new FileInfo(path).Length };
            var grouped = new Dictionary<string, Item>();

            using (var stream = File.OpenRead(path))
            {
                var bundle = WPFMAVrcaBundle.Open(stream);
                if (bundle.UsesContentEncryption)
                    throw new WPFMAVrcaException("This build is encrypted and cannot be read.");

                var nodes = bundle.Nodes.Where(n => (n.Flags & 4) != 0).ToList();
                for (int n = 0; n < nodes.Count; n++)
                {
                    EditorUtility.DisplayProgressBar("Build size explorer", "Reading " + nodes[n].Path, n / (float)Math.Max(1, nodes.Count));

                    WPFMASerializedFile file;
                    try
                    {
                        file = WPFMASerializedFile.Parse(bundle.ExtractNodeBytes(stream, nodes[n]));
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    foreach (var info in file.Objects)
                    {
                        if (info.Type == null)
                            continue;

                        string kind;
                        if (!Kinds.TryGetValue(info.Type.ClassId, out kind))
                            kind = "Other";

                        long bytes = info.Size + Streamed(file, info);
                        string name = SafeName(file, info);

                        string key = kind + "|" + name;
                        Item item;
                        if (!grouped.TryGetValue(key, out item))
                        {
                            item = new Item { Name = name, Kind = kind };
                            grouped.Add(key, item);
                        }
                        item.Bytes += bytes;

                        long total;
                        report.ByKind.TryGetValue(kind, out total);
                        report.ByKind[kind] = total + bytes;
                        report.ContentBytes += bytes;
                    }
                }
            }

            report.Items.AddRange(grouped.Values.Where(i => !string.IsNullOrEmpty(i.Name)).OrderByDescending(i => i.Bytes).Take(60));
            return report;
        }

        private static string SafeName(WPFMASerializedFile file, WPFMASerializedFile.ObjectInfo info)
        {
            try
            {
                return file.ReadString(info, "m_Name") ?? string.Empty;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        private static long Streamed(WPFMASerializedFile file, WPFMASerializedFile.ObjectInfo info)
        {
            try
            {
                int id = info.Type.ClassId;
                if (id == 28 || id == 43 || id == 89 || id == 117 || id == 187)
                {
                    var data = file.ReadField(info, "m_StreamData") as Dictionary<string, object>;
                    return data != null && data.ContainsKey("size") ? Convert.ToInt64(data["size"]) : 0;
                }

                if (id == 83)
                {
                    var resource = file.ReadField(info, "m_Resource") as Dictionary<string, object>;
                    return resource != null && resource.ContainsKey("m_Size") ? Convert.ToInt64(resource["m_Size"]) : 0;
                }
            }
            catch (Exception)
            {
            }

            return 0;
        }

        internal static UnityEngine.Object FindAsset(Item item)
        {
            string filter = item.Kind == "Texture" ? "t:Texture2D" : item.Kind == "Mesh" ? "t:Mesh"
                : item.Kind == "Audio" ? "t:AudioClip" : item.Kind == "Material" ? "t:Material" : item.Kind == "Shader" ? "t:Shader" : null;
            if (filter == null)
                return null;

            foreach (var guid in AssetDatabase.FindAssets(item.Name + " " + filter))
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);
                foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path))
                    if (asset != null && asset.name == item.Name)
                        return asset;
            }

            return null;
        }
    }

    internal static class WPFMABuildSizeSection
    {
        private const string PrefKey = "WPFMA.Tools.BuildSizeExpanded";

        private static WPFMABuildSizeExplorer.Report report;
        private static string error;
        private static Vector2 scroll;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Build size explorer",
                report == null ? "no build read yet" : Mb(report.FileBytes) + " download", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("What takes space in your build.", "After you build or test the world in VRChat's SDK, this opens that build and lists what takes the most " + "space, so you know exactly what to shrink."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            string last = WPFMABuildSizeExplorer.LastBuildPath();
            using (new EditorGUILayout.HorizontalScope())
            {
                using (new EditorGUI.DisabledScope(last == null))
                    if (GUILayout.Button(last == null ? "No build yet - use Build & Test first" : "Read the last build", GUILayout.Height(24f)))
                        EditorApplication.delayCall += () => Load(last);

                if (GUILayout.Button("Pick a .vrcw...", GUILayout.Width(110f), GUILayout.Height(24f)))
                {
                    string picked = EditorUtility.OpenFilePanel("Pick a world build", string.Empty, "vrcw");
                    if (!string.IsNullOrEmpty(picked))
                        EditorApplication.delayCall += () => Load(picked);
                }
            }

            if (!string.IsNullOrEmpty(error))
                EditorGUILayout.LabelField(error, WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));

            if (report == null)
                return;

            EditorGUILayout.Space(4f);
            bool android = report.Path.IndexOf("android", StringComparison.OrdinalIgnoreCase) >= 0;
            long limit = android ? 100L * 1024 * 1024 : 200L * 1024 * 1024;
            EditorGUILayout.LabelField(
                "Download size: " + Mb(report.FileBytes) + "  (" + Mb(report.ContentBytes) + " once unpacked)",
                new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = report.FileBytes > limit ? WPFMAToolSection.WarnAmber : WPFMAToolSection.OkGreen } });
            EditorGUILayout.LabelField(android ? "Quest builds must be under 100 MB." : "VRChat suggests keeping PC worlds under 200 MB.",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            EditorGUILayout.Space(4f);
            foreach (var pair in report.ByKind.OrderByDescending(p => p.Value).Take(8))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(pair.Key, GUILayout.Width(120f));
                    var bar = GUILayoutUtility.GetRect(0f, 14f, GUILayout.ExpandWidth(true));
                    bar.y += 2f;
                    EditorGUI.DrawRect(bar, WPFMAToolSection.ToolbarBackground);
                    EditorGUI.DrawRect(new Rect(bar.x, bar.y, bar.width * pair.Value / Math.Max(1f, report.ContentBytes), bar.height), WPFMAToolSection.AccentBlue);
                    EditorGUILayout.LabelField(Mb(pair.Value), WPFMAToolSection.Hint(WPFMAToolSection.MetaText), GUILayout.Width(70f));
                }
            }

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("Heaviest assets (unpacked size)", EditorStyles.boldLabel);
            scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(260f));
            foreach (var item in report.Items)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(item.Name, WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                    EditorGUILayout.LabelField(item.Kind, WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(80f));
                    EditorGUILayout.LabelField(Mb(item.Bytes), WPFMAToolSection.Hint(WPFMAToolSection.MetaText), GUILayout.Width(70f));
                    if (GUILayout.Button("Find", EditorStyles.miniButton, GUILayout.Width(40f)))
                    {
                        var asset = WPFMABuildSizeExplorer.FindAsset(item);
                        if (asset != null)
                        {
                            Selection.activeObject = asset;
                            EditorGUIUtility.PingObject(asset);
                        }
                    }
                }
            }
            EditorGUILayout.EndScrollView();
            EditorGUILayout.LabelField(new GUIContent("Textures are usually the fix.", "Textures are usually the fix - the texture optimizer on the Optimize page shrinks them."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
        }

        private static void Load(string path)
        {
            error = null;
            try
            {
                report = WPFMABuildSizeExplorer.Read(path);
            }
            catch (Exception e)
            {
                report = null;
                error = "Could not read the build: " + e.Message;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }

        private static string Mb(long bytes)
        {
            return (bytes / (1024.0 * 1024.0)).ToString("0.0") + " MB";
        }
    }
}
#endif
