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

namespace WPFMA.Vrca
{
    public static class WPFMARipReport
    {
        public static string Generate(string vrcaPath, string outputPath, Func<float, string, bool> onProgress,
            AssetBundle existingBundle = null)
        {
            var report = new StringBuilder();
            AssetBundle bundle = existingBundle;
            bool ownsBundle = false;

            try
            {
                Step(onProgress, 0.05f, "Reading container");
                WPFMASerializedFile cab = null;
                WriteContainer(report, vrcaPath, ref cab);
                if (cab != null)
                    WriteBuiltWith(report, cab);

                Step(onProgress, 0.2f, "Opening bundle");
                if (bundle == null)
                {
                    bundle = AssetBundle.LoadFromFile(vrcaPath);
                    ownsBundle = bundle != null;
                }

                if (bundle == null)
                {
                    report.AppendLine("Unity could not open this bundle, so only the container details above are available.");
                }
                else
                {
                    var root = bundle.LoadAllAssets<GameObject>().FirstOrDefault(g => g != null && g.transform.parent == null);
                    if (root == null)
                    {
                        report.AppendLine("The bundle contains no root GameObject.");
                    }
                    else
                    {
                        Step(onProgress, 0.3f, "Hierarchy");
                        WriteAvatar(report, root);
                        WriteComponents(report, root);

                        Step(onProgress, 0.45f, "Meshes");
                        WriteMeshes(report, root);

                        Step(onProgress, 0.6f, "Materials");
                        WriteMaterials(report, root);

                        Step(onProgress, 0.75f, "Textures");
                        WriteTextures(report, root);

                        Step(onProgress, 0.85f, "VRChat setup");
                        WriteVrchat(report, root);
                    }
                }

                if (cab != null)
                {
                    Step(onProgress, 0.92f, "Shaders");
                    WriteShaders(report, cab);

                    Step(onProgress, 0.97f, "Animators");
                    WriteAnimators(report, cab);
                }

                Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                File.WriteAllText(outputPath, report.ToString());
                return outputPath;
            }
            finally
            {
                if (ownsBundle && bundle != null)
                    bundle.Unload(true);
            }
        }

        private static void Step(Func<float, string, bool> onProgress, float fraction, string label)
        {
            if (onProgress != null && !onProgress(fraction, label))
                throw new OperationCanceledException();
        }

        private static void WriteContainer(StringBuilder report, string vrcaPath, ref WPFMASerializedFile cab)
        {
            var info = new FileInfo(vrcaPath);

            Header(report, "SOURCE");
            report.AppendLine("File            " + info.Name);
            report.AppendLine("Path            " + info.FullName);
            report.AppendLine("Size            " + Bytes(info.Length));
            report.AppendLine("Modified        " + info.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"));
            report.AppendLine("Report written  " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            report.AppendLine("Editor          Unity " + Application.unityVersion + ", target " + EditorUserBuildSettings.activeBuildTarget);
            report.AppendLine();

            try
            {
                using (var stream = new FileStream(vrcaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var container = WPFMAVrcaBundle.Open(stream);

                    Header(report, "CONTAINER");
                    report.AppendLine("Format          " + container.Signature + " v" + container.FormatVersion);
                    report.AppendLine("Built with      Unity " + container.UnityRevision);
                    report.AppendLine("Flags           0x" + container.Flags.ToString("x"));
                    report.AppendLine("Encrypted       " + container.UsesContentEncryption);
                    report.AppendLine("Directory       " + container.BlocksInfoCompression);
                    report.AppendLine("Blocks          " + container.Blocks.Count + "  (" +
                        string.Join(", ", container.Blocks.Select(b => b.Compression).Distinct()) + ")");
                    report.AppendLine("Unpacked size   " + Bytes(container.TotalUncompressedSize));
                    report.AppendLine();

                    report.AppendLine("Files inside the archive:");
                    foreach (var node in container.Nodes)
                        report.AppendLine("   " + node.Path.PadRight(52) + Bytes(node.Size));
                    report.AppendLine();

                    if (container.UsesContentEncryption)
                        return;

                    var serialized = container.Nodes.FirstOrDefault(n => (n.Flags & 4) != 0);
                    if (serialized != null)
                        cab = WPFMASerializedFile.Parse(container.ExtractNodeBytes(stream, serialized));
                }
            }
            catch (Exception e)
            {
                report.AppendLine("Container could not be parsed: " + e.Message);
                report.AppendLine();
            }

            if (cab == null)
                return;

            var byClass = cab.Objects.GroupBy(o => o.Type.ClassId)
                .OrderByDescending(g => g.Count())
                .Select(g => ClassName(g.Key) + " x" + g.Count());

            Header(report, "SERIALIZED OBJECTS");
            report.AppendLine("Total           " + cab.Objects.Count);
            report.AppendLine("Type trees      " + cab.HasTypeTrees);
            report.AppendLine("Breakdown       " + string.Join(", ", byClass));
            report.AppendLine();
        }

        /// <summary>The avatar systems it was built with, and what that means for the ripped copy.</summary>
        private static void WriteBuiltWith(StringBuilder report, WPFMASerializedFile cab)
        {
            var traces = new WPFMABundleSystems.Traces();
            WPFMABundleSystems.Collect(cab, traces);
            foreach (var info in cab.Objects.Where(o => o.Type != null && o.Type.ClassId == 48))
            {
                try
                {
                    string name = cab.ReadString(info, "m_ParsedForm", "m_Name");
                    if (!string.IsNullOrEmpty(name))
                        traces.Shaders.Add(name);
                }
                catch (Exception)
                {
                }
            }
            var systems = WPFMABundleSystems.Detect(traces);

            Header(report, "BUILT WITH");
            if (systems.Count == 0)
            {
                report.AppendLine("No VRCFury, Modular Avatar, GoGo Loco, face tracking, OSCmooth or optimizer traces found.");
                report.AppendLine();
                return;
            }

            foreach (var system in systems)
                report.AppendLine((system.Name + " ").PadRight(34, '.') + " " + system.Evidence);
            report.AppendLine();
            report.AppendLine(WPFMABundleSystems.BakedNote);
            report.AppendLine(WPFMABundleSystems.StackWarning);
            report.AppendLine();
        }

        private static void WriteAvatar(StringBuilder report, GameObject root)
        {
            var transforms = root.GetComponentsInChildren<Transform>(true);
            var animator = root.GetComponentInChildren<Animator>(true);

            Header(report, "AVATAR");
            report.AppendLine("Root            " + root.name);
            report.AppendLine("GameObjects     " + transforms.Length);
            report.AppendLine("Max depth       " + transforms.Max(t => Depth(t, root.transform)));

            if (animator != null)
            {
                report.AppendLine("Animator        avatar=" + (animator.avatar != null ? animator.avatar.name : "<none>") +
                    "  humanoid=" + (animator.avatar != null && animator.avatar.isHuman) +
                    "  valid=" + (animator.avatar != null && animator.avatar.isValid));
            }

            var pipeline = root.GetComponents<Component>()
                .FirstOrDefault(c => c != null && c.GetType().Name == "PipelineManager");
            if (pipeline != null)
            {
                var blueprint = new SerializedObject(pipeline).FindProperty("blueprintId");
                if (blueprint != null)
                    report.AppendLine("Blueprint ID    " + blueprint.stringValue);
            }

            report.AppendLine();
        }

        private static int Depth(Transform t, Transform root)
        {
            int depth = 0;
            while (t != null && t != root)
            {
                depth++;
                t = t.parent;
            }
            return depth;
        }

        private static void WriteComponents(StringBuilder report, GameObject root)
        {
            var census = new Dictionary<string, int>();
            int missing = 0;

            foreach (var t in root.GetComponentsInChildren<Transform>(true))
            {
                foreach (var c in t.GetComponents<Component>())
                {
                    if (c == null)
                    {
                        missing++;
                        continue;
                    }

                    string name = c.GetType().Name;
                    int count;
                    census.TryGetValue(name, out count);
                    census[name] = count + 1;
                }
            }

            Header(report, "COMPONENTS");
            foreach (var entry in census.OrderByDescending(e => e.Value))
                report.AppendLine("   " + (entry.Key + " ").PadRight(40, '.') + " " + entry.Value);
            if (missing > 0)
                report.AppendLine("   " + "<script not resolvable in this project> ".PadRight(40, '.') + " " + missing);
            report.AppendLine();
        }

        private static void WriteMeshes(StringBuilder report, GameObject root)
        {
            var seen = new List<Mesh>();

            foreach (var smr in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                if (smr.sharedMesh != null && !seen.Contains(smr.sharedMesh))
                    seen.Add(smr.sharedMesh);

            foreach (var filter in root.GetComponentsInChildren<MeshFilter>(true))
                if (filter.sharedMesh != null && !seen.Contains(filter.sharedMesh))
                    seen.Add(filter.sharedMesh);

            Header(report, "MESHES (" + seen.Count + ")");

            long totalVerts = 0;
            long totalTris = 0;

            foreach (var mesh in seen.OrderByDescending(m => m.vertexCount))
            {
                totalVerts += mesh.vertexCount;
                totalTris += mesh.triangles.Length / 3;

                report.AppendLine(mesh.name);
                report.AppendLine("   vertices " + mesh.vertexCount +
                    "   triangles " + (mesh.triangles.Length / 3) +
                    "   submeshes " + mesh.subMeshCount +
                    "   blendshapes " + mesh.blendShapeCount +
                    "   bones " + mesh.bindposes.Length);

                if (mesh.blendShapeCount > 0)
                {
                    var names = Enumerable.Range(0, mesh.blendShapeCount).Select(mesh.GetBlendShapeName);
                    report.AppendLine("   shapes: " + Truncate(string.Join(", ", names), 400));
                }
            }

            report.AppendLine();
            report.AppendLine("Totals: " + totalVerts + " vertices, " + totalTris + " triangles");
            report.AppendLine();
        }

        private static void WriteMaterials(StringBuilder report, GameObject root)
        {
            var materials = root.GetComponentsInChildren<Renderer>(true)
                .SelectMany(r => r.sharedMaterials)
                .Where(m => m != null)
                .Distinct()
                .OrderBy(m => m.name)
                .ToList();

            Header(report, "MATERIALS (" + materials.Count + ")");
            report.AppendLine("Every property below is the value the original avatar shipped with.");
            report.AppendLine();

            foreach (var material in materials)
            {
                var shader = material.shader;
                report.AppendLine(new string('-', 78));
                report.AppendLine("Material   " + material.name);
                report.AppendLine("Shader     " + (shader != null ? shader.name : "<none>"));

                if (shader != null)
                {
                    string family = WPFMAShaderResolver.RecoverBaseName(shader.name);
                    if (family != shader.name)
                        report.AppendLine("Derived    " + family);
                }

                report.AppendLine("Queue      " + material.renderQueue);

                var keywords = material.shaderKeywords;
                if (keywords != null && keywords.Length > 0)
                    report.AppendLine("Keywords   " + Truncate(string.Join(", ", keywords), 400));

                if (shader == null)
                {
                    report.AppendLine();
                    continue;
                }

                report.AppendLine();
                int count = shader.GetPropertyCount();
                for (int i = 0; i < count; i++)
                {
                    string name = shader.GetPropertyName(i);
                    var type = shader.GetPropertyType(i);
                    string value;

                    switch (type)
                    {
                        case UnityEngine.Rendering.ShaderPropertyType.Texture:
                            var texture = material.GetTexture(name);
                            if (texture == null)
                            {
                                value = "<none>";
                            }
                            else
                            {
                                value = texture.name + "  " + texture.width + "x" + texture.height +
                                    "  " + texture.GetType().Name;
                                var scale = material.GetTextureScale(name);
                                var offset = material.GetTextureOffset(name);
                                if (scale != Vector2.one || offset != Vector2.zero)
                                    value += "  tiling=" + scale + " offset=" + offset;
                            }
                            break;

                        case UnityEngine.Rendering.ShaderPropertyType.Color:
                            var c = material.GetColor(name);
                            value = string.Format("RGBA({0:F3}, {1:F3}, {2:F3}, {3:F3})", c.r, c.g, c.b, c.a);
                            break;

                        case UnityEngine.Rendering.ShaderPropertyType.Vector:
                            value = material.GetVector(name).ToString("F3");
                            break;

                        case UnityEngine.Rendering.ShaderPropertyType.Float:
                        case UnityEngine.Rendering.ShaderPropertyType.Range:
                            value = material.GetFloat(name).ToString("F4");
                            break;

                        default:
                            value = "<unsupported>";
                            break;
                    }

                    report.AppendLine("   " + (name + " ").PadRight(42, '.') + " " + value);
                }

                report.AppendLine();
            }
        }

        private static void WriteTextures(StringBuilder report, GameObject root)
        {
            var textures = new List<Texture>();

            foreach (var material in root.GetComponentsInChildren<Renderer>(true)
                         .SelectMany(r => r.sharedMaterials).Where(m => m != null).Distinct())
            {
                if (material.shader == null)
                    continue;

                foreach (var name in material.GetTexturePropertyNames())
                {
                    var texture = material.GetTexture(name);
                    if (texture != null && !textures.Contains(texture))
                        textures.Add(texture);
                }
            }

            Header(report, "TEXTURES (" + textures.Count + ")");

            long memory = 0;
            foreach (var texture in textures.OrderByDescending(t => t.width * t.height))
            {
                long size = UnityEngine.Profiling.Profiler.GetRuntimeMemorySizeLong(texture);
                memory += size;

                string format = texture is Texture2D ? ((Texture2D)texture).format.ToString() : texture.GetType().Name;
                report.AppendLine("   " + (texture.name + " ").PadRight(44, '.') + " " +
                    (texture.width + "x" + texture.height).PadRight(12) + format.PadRight(18) + Bytes(size));
            }

            report.AppendLine();
            report.AppendLine("Total texture memory: " + Bytes(memory));
            report.AppendLine();
        }

        private static void WriteVrchat(StringBuilder report, GameObject root)
        {
            var descriptor = root.GetComponents<Component>()
                .FirstOrDefault(c => c != null && c.GetType().Name == "VRCAvatarDescriptor");

            Header(report, "VRCHAT SETUP");

            if (descriptor == null)
            {
                report.AppendLine("No VRCAvatarDescriptor resolved. Install the VRChat SDK to read this section.");
                report.AppendLine();
                return;
            }

            var so = new SerializedObject(descriptor);

            var menu = so.FindProperty("expressionsMenu");
            var parameters = so.FindProperty("expressionParameters");
            report.AppendLine("Expressions menu       " + Describe(menu));
            report.AppendLine("Expression parameters  " + Describe(parameters));

            var layers = so.FindProperty("baseAnimationLayers");
            if (layers != null && layers.isArray)
            {
                report.AppendLine();
                report.AppendLine("Playable layers:");
                for (int i = 0; i < layers.arraySize; i++)
                {
                    var element = layers.GetArrayElementAtIndex(i);
                    var controller = element.FindPropertyRelative("animatorController");
                    var mask = element.FindPropertyRelative("mask");
                    report.AppendLine("   [" + i + "] " +
                        (controller != null ? Describe(controller) : "<none>") +
                        (mask != null && mask.objectReferenceValue != null ? "   mask=" + mask.objectReferenceValue.name : ""));
                }
            }

            if (parameters != null && parameters.objectReferenceValue != null)
            {
                var ps = new SerializedObject(parameters.objectReferenceValue).FindProperty("parameters");
                if (ps != null && ps.isArray)
                {
                    report.AppendLine();
                    report.AppendLine("Expression parameters (" + ps.arraySize + "):");
                    for (int i = 0; i < ps.arraySize; i++)
                    {
                        var p = ps.GetArrayElementAtIndex(i);
                        report.AppendLine("   " + (Str(p, "name") + " ").PadRight(38, '.') +
                            " type=" + Int(p, "valueType") +
                            " default=" + Flt(p, "defaultValue") +
                            " saved=" + Bool(p, "saved") +
                            " synced=" + Bool(p, "networkSynced"));
                    }
                }
            }

            if (menu != null && menu.objectReferenceValue != null)
            {
                report.AppendLine();
                report.AppendLine("Expressions menu tree:");
                WriteMenu(report, menu.objectReferenceValue, "   ", 0, new HashSet<UnityEngine.Object>());
            }

            var physBones = root.GetComponentsInChildren<Component>(true)
                .Where(c => c != null && c.GetType().Name == "VRCPhysBone").ToList();
            if (physBones.Count > 0)
            {
                report.AppendLine();
                report.AppendLine("PhysBones (" + physBones.Count + "):");
                foreach (var bone in physBones.Take(60))
                {
                    var bso = new SerializedObject(bone);
                    report.AppendLine("   " + (bone.gameObject.name + " ").PadRight(34, '.') +
                        " pull=" + Flt(bso, "pull") + " spring=" + Flt(bso, "spring") +
                        " stiffness=" + Flt(bso, "stiffness") + " radius=" + Flt(bso, "radius"));
                }
                if (physBones.Count > 60)
                    report.AppendLine("   … and " + (physBones.Count - 60) + " more");
            }

            report.AppendLine();
        }

        private static void WriteMenu(StringBuilder report, UnityEngine.Object menu, string indent, int depth,
            HashSet<UnityEngine.Object> visited)
        {
            if (menu == null || depth > 6 || !visited.Add(menu))
                return;

            var controls = new SerializedObject(menu).FindProperty("controls");
            if (controls == null || !controls.isArray)
                return;

            for (int i = 0; i < controls.arraySize; i++)
            {
                var control = controls.GetArrayElementAtIndex(i);
                var parameter = control.FindPropertyRelative("parameter");
                string parameterName = parameter != null ? Str(parameter, "name") : "";

                report.AppendLine(indent + Str(control, "name") +
                    "   [type " + Int(control, "type") + "]" +
                    (string.IsNullOrEmpty(parameterName) ? "" : "  param=" + parameterName) +
                    "  value=" + Flt(control, "value"));

                var sub = control.FindPropertyRelative("subMenu");
                if (sub != null && sub.objectReferenceValue != null)
                    WriteMenu(report, sub.objectReferenceValue, indent + "   ", depth + 1, visited);
            }
        }

        private static void WriteShaders(StringBuilder report, WPFMASerializedFile cab)
        {
            var shaders = cab.Objects.Where(o => o.Type.ClassId == 48).ToList();
            Header(report, "SHADERS (" + shaders.Count + ")");
            report.AppendLine("Read from the bundle's serialized data. The compiled programs cannot be turned");
            report.AppendLine("back into source, but the full ShaderLab definition below is intact.");
            report.AppendLine();

            foreach (var info in shaders)
            {
                Dictionary<string, object> value;
                try
                {
                    value = cab.ReadObject(info) as Dictionary<string, object>;
                }
                catch (Exception)
                {
                    continue;
                }

                if (value == null)
                    continue;

                var parsed = Get(value, "m_ParsedForm");
                if (parsed == null)
                    continue;

                string name = parsed.ContainsKey("m_Name") ? parsed["m_Name"] as string : "<unnamed>";
                report.AppendLine(new string('-', 78));
                report.AppendLine("Shader     " + name);

                string family = WPFMAShaderResolver.RecoverBaseName(name);
                if (family != name)
                    report.AppendLine("Derived    " + family);

                var props = Get(parsed, "m_PropInfo");
                var propList = props != null ? props["m_Props"] as List<object> : null;
                report.AppendLine("Properties " + (propList != null ? propList.Count : 0));

                var keywords = parsed.ContainsKey("m_KeywordNames") ? parsed["m_KeywordNames"] as List<object> : null;
                if (keywords != null && keywords.Count > 0)
                    report.AppendLine("Keywords   " + Truncate(string.Join(", ", keywords.Select(k => k.ToString())), 400));

                string fallback = parsed.ContainsKey("m_FallbackName") ? parsed["m_FallbackName"] as string : null;
                if (!string.IsNullOrEmpty(fallback))
                    report.AppendLine("Fallback   " + fallback);

                var subShaders = parsed.ContainsKey("m_SubShaders") ? parsed["m_SubShaders"] as List<object> : null;
                if (subShaders != null)
                {
                    for (int s = 0; s < subShaders.Count; s++)
                    {
                        var sub = subShaders[s] as Dictionary<string, object>;
                        if (sub == null)
                            continue;

                        var passes = sub.ContainsKey("m_Passes") ? sub["m_Passes"] as List<object> : null;
                        report.AppendLine("SubShader " + s + "   passes=" + (passes != null ? passes.Count : 0) +
                            "   tags: " + Tags(sub.ContainsKey("m_Tags") ? sub["m_Tags"] : null));
                    }
                }

                var blob = value.ContainsKey("compressedBlob") ? value["compressedBlob"] as List<object> : null;
                var decompressed = value.ContainsKey("decompressedLengths") ? value["decompressedLengths"] as List<object> : null;
                if (blob != null)
                {
                    long expanded = 0;
                    if (decompressed != null)
                        foreach (var platform in decompressed)
                            foreach (var length in (platform as List<object> ?? new List<object>()))
                                expanded += Convert.ToInt64(length);

                    report.AppendLine("Programs   " + Bytes(blob.Count) + " compiled" +
                        (expanded > 0 ? " → " + Bytes(expanded) + " expanded" : ""));
                }

                if (propList != null && propList.Count > 0)
                {
                    report.AppendLine();
                    foreach (var entry in propList)
                    {
                        var p = entry as Dictionary<string, object>;
                        if (p == null)
                            continue;

                        report.AppendLine("   " + ((p.ContainsKey("m_Name") ? p["m_Name"] : "?") + " ").ToString().PadRight(42, '.') +
                            " type=" + (p.ContainsKey("m_Type") ? p["m_Type"] : "?") +
                            "  flags=" + (p.ContainsKey("m_Flags") ? p["m_Flags"] : "?") +
                            "  default=" + (p.ContainsKey("m_DefValue[0]") ? p["m_DefValue[0]"] : "?"));
                    }
                }

                report.AppendLine();
            }
        }

        private static string Tags(object tagsObject)
        {
            var tags = tagsObject as Dictionary<string, object>;
            if (tags == null)
                return "<none>";

            var inner = tags.ContainsKey("tags") ? tags["tags"] as List<object> : null;
            if (inner == null || inner.Count == 0)
                return "<none>";

            return string.Join(", ", inner.OfType<Dictionary<string, object>>()
                .Select(t => t["first"] + "=" + t["second"]));
        }

        private static void WriteAnimators(StringBuilder report, WPFMASerializedFile cab)
        {
            var controllers = cab.Objects.Where(o => o.Type.ClassId == 91).ToList();
            Header(report, "ANIMATOR CONTROLLERS (" + controllers.Count + ")");

            foreach (var info in controllers)
            {
                Dictionary<string, object> value;
                try
                {
                    value = cab.ReadObject(info) as Dictionary<string, object>;
                }
                catch (Exception)
                {
                    continue;
                }

                if (value == null)
                    continue;

                string name = value.ContainsKey("m_Name") ? value["m_Name"] as string : "<unnamed>";
                var controller = Get(value, "m_Controller");
                if (controller == null)
                    continue;

                var layers = controller.ContainsKey("m_LayerArray") ? controller["m_LayerArray"] as List<object> : null;
                var machines = controller.ContainsKey("m_StateMachineArray") ? controller["m_StateMachineArray"] as List<object> : null;

                var tos = new Dictionary<uint, string>();
                var tosList = value.ContainsKey("m_TOS") ? value["m_TOS"] as List<object> : null;
                if (tosList != null)
                {
                    foreach (var entry in tosList.OfType<Dictionary<string, object>>())
                        tos[Convert.ToUInt32(entry["first"])] = entry["second"] as string;
                }

                report.AppendLine(new string('-', 78));
                report.AppendLine("Controller " + name);
                report.AppendLine("Layers     " + (layers != null ? layers.Count : 0));

                var clips = value.ContainsKey("m_AnimationClips") ? value["m_AnimationClips"] as List<object> : null;
                report.AppendLine("Clips      " + (clips != null ? clips.Count : 0));

                if (layers == null || machines == null)
                {
                    report.AppendLine();
                    continue;
                }

                for (int i = 0; i < layers.Count; i++)
                {
                    var layer = Data(layers[i]);
                    int machineIndex = layer.ContainsKey("m_StateMachineIndex") ? Convert.ToInt32(layer["m_StateMachineIndex"]) : -1;
                    string layerName = layer.ContainsKey("m_Binding") && tos.ContainsKey(Convert.ToUInt32(layer["m_Binding"]))
                        ? tos[Convert.ToUInt32(layer["m_Binding"])]
                        : "Layer " + i;

                    int states = 0;
                    int transitions = 0;
                    if (machineIndex >= 0 && machineIndex < machines.Count)
                    {
                        var machine = Data(machines[machineIndex]);
                        var stateArray = machine.ContainsKey("m_StateConstantArray") ? machine["m_StateConstantArray"] as List<object> : null;
                        if (stateArray != null)
                        {
                            states = stateArray.Count;
                            foreach (var state in stateArray)
                            {
                                var sd = Data(state);
                                var t = sd.ContainsKey("m_TransitionConstantArray") ? sd["m_TransitionConstantArray"] as List<object> : null;
                                if (t != null)
                                    transitions += t.Count;
                            }
                        }
                    }

                    report.AppendLine("   [" + i + "] " + (layerName + " ").PadRight(38, '.') +
                        " states=" + states + " transitions=" + transitions);
                }

                report.AppendLine();
            }
        }

        private static Dictionary<string, object> Get(Dictionary<string, object> map, string key)
        {
            object value;
            return map.TryGetValue(key, out value) ? value as Dictionary<string, object> : null;
        }

        private static Dictionary<string, object> Data(object value)
        {
            var d = value as Dictionary<string, object>;
            if (d == null)
                return new Dictionary<string, object>();

            object inner;
            if (d.Count == 1 && d.TryGetValue("data", out inner))
                return inner as Dictionary<string, object> ?? d;

            return d;
        }

        private static string Describe(SerializedProperty property)
        {
            if (property == null || property.objectReferenceValue == null)
                return "<none>";
            return property.objectReferenceValue.name;
        }

        private static string Str(SerializedProperty parent, string name)
        {
            var p = parent.FindPropertyRelative(name);
            return p != null ? p.stringValue : "";
        }

        private static string Int(SerializedProperty parent, string name)
        {
            var p = parent.FindPropertyRelative(name);
            return p != null ? p.intValue.ToString() : "?";
        }

        private static string Flt(SerializedProperty parent, string name)
        {
            var p = parent.FindPropertyRelative(name);
            return p != null ? p.floatValue.ToString("F3") : "?";
        }

        private static string Bool(SerializedProperty parent, string name)
        {
            var p = parent.FindPropertyRelative(name);
            return p != null ? p.boolValue.ToString() : "?";
        }

        private static string Flt(SerializedObject so, string name)
        {
            var p = so.FindProperty(name);
            return p != null ? p.floatValue.ToString("F3") : "?";
        }

        private static void Header(StringBuilder report, string title)
        {
            report.AppendLine(new string('=', 78));
            report.AppendLine(title);
            report.AppendLine(new string('=', 78));
        }

        private static string Truncate(string value, int max)
        {
            if (string.IsNullOrEmpty(value) || value.Length <= max)
                return value;
            return value.Substring(0, max) + " … (+" + (value.Length - max) + " chars)";
        }

        private static string Bytes(long value)
        {
            if (value < 1024L) return value + " B";
            if (value < 1024L * 1024L) return (value / 1024f).ToString("F1") + " KB";
            if (value < 1024L * 1024L * 1024L) return (value / (1024f * 1024f)).ToString("F1") + " MB";
            return (value / (1024f * 1024f * 1024f)).ToString("F2") + " GB";
        }

        private static string ClassName(int classId)
        {
            switch (classId)
            {
                case 1: return "GameObject";
                case 4: return "Transform";
                case 21: return "Material";
                case 23: return "MeshRenderer";
                case 28: return "Texture2D";
                case 33: return "MeshFilter";
                case 43: return "Mesh";
                case 48: return "Shader";
                case 74: return "AnimationClip";
                case 82: return "AudioSource";
                case 83: return "AudioClip";
                case 89: return "Cubemap";
                case 90: return "Avatar";
                case 91: return "AnimatorController";
                case 95: return "Animator";
                case 111: return "Animation";
                case 114: return "MonoBehaviour";
                case 115: return "MonoScript";
                case 137: return "SkinnedMeshRenderer";
                case 198: return "ParticleSystem";
                case 199: return "ParticleSystemRenderer";
                case 319: return "AvatarMask";
                default: return "Class" + classId;
            }
        }
    }
}
#endif
