// 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.Text;

namespace WPFMA.Vrca
{
    public sealed class WPFMASerializedFile
    {
        public sealed class TypeTreeNode
        {
            public string Type;
            public string Name;
            public int Size;
            public int MetaFlag;
            public byte Level;
            public readonly List<TypeTreeNode> Children = new List<TypeTreeNode>();
        }

        public sealed class SerializedType
        {
            public int ClassId;
            public TypeTreeNode Tree;
        }

        public sealed class ObjectInfo
        {
            public long PathId;
            public long Offset;
            public uint Size;
            public SerializedType Type;
        }

        public int FormatVersion { get; private set; }
        public string UnityVersion { get; private set; }
        public bool HasTypeTrees { get; private set; }
        public List<ObjectInfo> Objects { get; private set; }

        private byte[] data;
        private bool littleEndian;

        private static readonly Dictionary<uint, string> CommonStrings = BuildCommonStrings();

        private static Dictionary<uint, string> BuildCommonStrings()
        {
            const string blob =
                "AABB\0AnimationClip\0AnimationCurve\0AnimationState\0Array\0Base\0BitField\0bitset\0bool\0char\0" +
                "ColorRGBA\0Component\0data\0deque\0double\0dynamic_array\0FastPropertyName\0first\0float\0Font\0" +
                "GameObject\0Generic Mono\0GradientNEW\0GUID\0GUIStyle\0int\0list\0long long\0map\0Matrix4x4f\0" +
                "MdFour\0MonoBehaviour\0MonoScript\0m_ByteSize\0m_Curve\0m_EditorClassIdentifier\0m_EditorHideFlags\0" +
                "m_Enabled\0m_ExtensionPtr\0m_GameObject\0m_Index\0m_IsArray\0m_IsStatic\0m_MetaFlag\0m_Name\0" +
                "m_ObjectHideFlags\0m_PrefabInternal\0m_PrefabParentObject\0m_Script\0m_StaticEditorFlags\0m_Type\0" +
                "m_Version\0Object\0pair\0PPtr<Component>\0PPtr<GameObject>\0PPtr<Material>\0PPtr<MonoBehaviour>\0" +
                "PPtr<MonoScript>\0PPtr<Object>\0PPtr<Prefab>\0PPtr<Sprite>\0PPtr<TextAsset>\0PPtr<Texture>\0" +
                "PPtr<Texture2D>\0PPtr<Transform>\0Prefab\0Quaternionf\0Rectf\0RectInt\0RectOffset\0second\0set\0" +
                "short\0size\0SInt16\0SInt32\0SInt64\0SInt8\0staticvector\0string\0TextAsset\0TextMesh\0Texture\0" +
                "Texture2D\0Transform\0TypelessData\0UInt16\0UInt32\0UInt64\0UInt8\0unsigned int\0unsigned long long\0" +
                "unsigned short\0vector\0Vector2f\0Vector3f\0Vector4f\0m_ScriptingClassIdentifier\0Gradient\0" +
                "Type*\0int2_storage\0int3_storage\0BoundsInt\0m_CorrespondingSourceObject\0m_PrefabInstance\0" +
                "m_PrefabAsset\0FileSize\0Hash128\0";

            var table = new Dictionary<uint, string>();
            uint offset = 0;
            foreach (var entry in blob.Split('\0'))
            {
                table[offset] = entry;
                offset += (uint)entry.Length + 1;
            }

            return table;
        }

        private sealed class Cursor
        {
            public byte[] D;
            public int P;
            public bool Little;

            public void Align(int n)
            {
                int r = P % n;
                if (r != 0)
                    P += n - r;
            }

            public byte U8() { return D[P++]; }

            public byte[] Raw(int n)
            {
                var b = new byte[n];
                Buffer.BlockCopy(D, P, b, 0, n);
                P += n;
                return b;
            }

            public void Skip(int n) { P += n; }

            public short I16() { return (short)U16(); }

            public ushort U16()
            {
                ushort v = Little
                    ? (ushort)(D[P] | (D[P + 1] << 8))
                    : (ushort)((D[P] << 8) | D[P + 1]);
                P += 2;
                return v;
            }

            public int I32() { return (int)U32(); }

            public uint U32()
            {
                uint v = Little
                    ? (uint)(D[P] | (D[P + 1] << 8) | (D[P + 2] << 16) | (D[P + 3] << 24))
                    : (uint)((D[P] << 24) | (D[P + 1] << 16) | (D[P + 2] << 8) | D[P + 3]);
                P += 4;
                return v;
            }

            public long I64() { return (long)U64(); }

            public ulong U64()
            {
                ulong lo, hi;
                if (Little)
                {
                    lo = U32();
                    hi = U32();
                }
                else
                {
                    hi = U32();
                    lo = U32();
                }
                return lo | (hi << 32);
            }

            public float F32()
            {
                var b = Raw(4);
                if (!Little)
                    Array.Reverse(b);
                return BitConverter.ToSingle(b, 0);
            }

            public double F64()
            {
                var b = Raw(8);
                if (!Little)
                    Array.Reverse(b);
                return BitConverter.ToDouble(b, 0);
            }

            public string CString()
            {
                int e = P;
                while (D[e] != 0)
                    e++;
                string s = Encoding.UTF8.GetString(D, P, e - P);
                P = e + 1;
                return s;
            }
        }

        public static WPFMASerializedFile Parse(byte[] fileData)
        {
            var sf = new WPFMASerializedFile { data = fileData };

            var h = new Cursor { D = fileData, Little = false };
            h.U32();
            h.U32();
            sf.FormatVersion = h.I32();
            h.U32();

            if (sf.FormatVersion < 17 || sf.FormatVersion > 22)
                throw new WPFMAVrcaException("Unsupported SerializedFile version " + sf.FormatVersion + ".");

            byte endianness = h.U8();
            h.Skip(3);

            long dataOffset;
            if (sf.FormatVersion >= 22)
            {
                h.U32();
                h.I64();
                dataOffset = h.I64();
                h.I64();
            }
            else
            {
                var legacy = new Cursor { D = fileData, Little = false };
                legacy.U32();
                legacy.U32();
                legacy.U32();
                dataOffset = legacy.U32();
            }

            var r = new Cursor { D = fileData, Little = endianness == 0, P = h.P };
            sf.littleEndian = endianness == 0;

            sf.UnityVersion = r.CString();
            r.I32();
            sf.HasTypeTrees = r.U8() != 0;

            if (!sf.HasTypeTrees)
                throw new WPFMAVrcaException("This bundle was built without type trees, so its objects cannot be read generically.");

            int typeCount = r.I32();
            var types = new List<SerializedType>(typeCount);
            for (int i = 0; i < typeCount; i++)
                types.Add(ReadType(r, sf.FormatVersion));

            int objectCount = r.I32();
            sf.Objects = new List<ObjectInfo>(objectCount);
            for (int i = 0; i < objectCount; i++)
            {
                r.Align(4);
                var o = new ObjectInfo();
                o.PathId = r.I64();
                o.Offset = dataOffset + (sf.FormatVersion >= 22 ? r.I64() : r.U32());
                o.Size = r.U32();
                int typeIndex = r.I32();
                o.Type = types[typeIndex];
                sf.Objects.Add(o);
            }

            return sf;
        }

        private static SerializedType ReadType(Cursor r, int version)
        {
            var t = new SerializedType();
            t.ClassId = r.I32();
            r.U8();
            r.I16();
            if (t.ClassId == 114)
                r.Skip(16);
            r.Skip(16);

            int nodeCount = r.I32();
            int stringBufferSize = r.I32();

            var flat = new List<TypeTreeNode>(nodeCount);
            var typeOffsets = new uint[nodeCount];
            var nameOffsets = new uint[nodeCount];

            for (int i = 0; i < nodeCount; i++)
            {
                var n = new TypeTreeNode();
                r.U16();
                n.Level = r.U8();
                r.U8();
                typeOffsets[i] = r.U32();
                nameOffsets[i] = r.U32();
                n.Size = r.I32();
                r.U32();
                n.MetaFlag = r.I32();
                if (version >= 19)
                    r.U64();
                flat.Add(n);
            }

            byte[] stringBuffer = r.Raw(stringBufferSize);

            for (int i = 0; i < nodeCount; i++)
            {
                flat[i].Type = ResolveString(stringBuffer, typeOffsets[i]);
                flat[i].Name = ResolveString(stringBuffer, nameOffsets[i]);
            }

            t.Tree = flat[0];
            var stack = new List<TypeTreeNode> { flat[0] };
            for (int i = 1; i < nodeCount; i++)
            {
                var n = flat[i];
                while (stack.Count > n.Level)
                    stack.RemoveAt(stack.Count - 1);
                stack[stack.Count - 1].Children.Add(n);
                stack.Add(n);
            }

            if (version >= 21)
            {
                int dependencyCount = r.I32();
                r.Skip(dependencyCount * 4);
            }

            return t;
        }

        private static string ResolveString(byte[] buffer, uint offset)
        {
            if ((offset & 0x80000000u) != 0)
            {
                string known;
                return CommonStrings.TryGetValue(offset & 0x7FFFFFFFu, out known)
                    ? known
                    : "<common:" + (offset & 0x7FFFFFFFu) + ">";
            }

            int start = (int)offset;
            int end = start;
            while (buffer[end] != 0)
                end++;
            return Encoding.UTF8.GetString(buffer, start, end - start);
        }

        public object ReadObject(ObjectInfo info)
        {
            var r = new Cursor { D = data, Little = littleEndian, P = (int)info.Offset };
            return ReadValue(r, info.Type.Tree);
        }

        public string ReadString(ObjectInfo info, params string[] path)
        {
            return ReadField(info, path) as string;
        }

        public object ReadField(ObjectInfo info, params string[] path)
        {
            if (info.Type == null || info.Type.Tree == null || path == null || path.Length == 0)
                return null;

            var r = new Cursor { D = data, Little = littleEndian, P = (int)info.Offset };
            var node = info.Type.Tree;

            for (int depth = 0; ; depth++)
            {
                TypeTreeNode next = null;
                foreach (var child in node.Children)
                {
                    if (child.Name == path[depth])
                    {
                        next = child;
                        break;
                    }

                    SkipValue(r, child);
                }

                if (next == null)
                    return null;

                if (depth == path.Length - 1)
                    return ReadValue(r, next);

                if (next.Children.Count > 0 && next.Children[0].Type == "Array")
                    return null;

                node = next;
            }
        }

        private static void SkipValue(Cursor r, TypeTreeNode node)
        {
            bool align = (node.MetaFlag & 0x4000) != 0;

            switch (node.Type)
            {
                case "string":
                    r.Skip(r.I32());
                    r.Align(4);
                    align = false;
                    break;

                case "TypelessData":
                    r.Skip(r.I32());
                    align = false;
                    break;

                default:
                    if (node.Children.Count == 0)
                    {
                        r.Skip(Math.Max(0, node.Size));
                    }
                    else if (node.Children[0].Type == "Array")
                    {
                        var arrayNode = node.Children[0];
                        int count = r.I32();
                        var element = arrayNode.Children[1];

                        if (element.Children.Count == 0 && element.Size > 0 && element.Type != "string" &&
                            (element.MetaFlag & 0x4000) == 0)
                        {
                            r.Skip(checked(count * element.Size));
                        }
                        else
                        {
                            for (int i = 0; i < count; i++)
                                SkipValue(r, element);
                        }

                        if ((arrayNode.MetaFlag & 0x4000) != 0)
                            r.Align(4);
                    }
                    else
                    {
                        foreach (var child in node.Children)
                            SkipValue(r, child);
                    }
                    break;
            }

            if (align)
                r.Align(4);
        }

        private static object ReadValue(Cursor r, TypeTreeNode node)
        {
            string t = node.Type;
            bool align = (node.MetaFlag & 0x4000) != 0;
            object v;

            switch (t)
            {
                case "int":
                case "SInt32": v = r.I32(); break;
                case "unsigned int":
                case "UInt32":
                case "Type*": v = r.U32(); break;
                case "SInt64":
                case "long long": v = r.I64(); break;
                case "UInt64":
                case "unsigned long long":
                case "FileSize": v = r.U64(); break;
                case "SInt16":
                case "short": v = r.I16(); break;
                case "UInt16":
                case "unsigned short": v = r.U16(); break;
                case "SInt8": v = (sbyte)r.U8(); break;
                case "UInt8":
                case "char": v = r.U8(); break;
                case "bool": v = r.U8() != 0; break;
                case "float": v = r.F32(); break;
                case "double": v = r.F64(); break;

                case "string":
                    {
                        int n = r.I32();
                        v = Encoding.UTF8.GetString(r.Raw(n));
                        r.Align(4);
                        align = false;
                        break;
                    }

                case "TypelessData":
                    {
                        int n = r.I32();
                        v = r.Raw(n);
                        align = false;
                        break;
                    }

                default:
                    if (node.Children.Count > 0 && node.Children[0].Type == "Array")
                    {
                        var arrayNode = node.Children[0];
                        int count = r.I32();
                        var element = arrayNode.Children[1];
                        var list = new List<object>(Math.Max(0, count));
                        for (int i = 0; i < count; i++)
                            list.Add(ReadValue(r, element));
                        if ((arrayNode.MetaFlag & 0x4000) != 0)
                            r.Align(4);
                        v = list;
                    }
                    else
                    {
                        var map = new Dictionary<string, object>(node.Children.Count);
                        foreach (var child in node.Children)
                            map[child.Name] = ReadValue(r, child);
                        v = map;
                    }
                    break;
            }

            if (align)
                r.Align(4);
            return v;
        }
    }
}
#endif
