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

namespace WPFMA.Vrca
{
    internal static class WPFMAStaticBatch
    {
        private const string CombinedPrefix = "Combined Mesh";

        internal static int Split(GameObject root, List<string> warnings)
        {
            if (root == null)
                return 0;

            int split = 0;
            var extracted = new Dictionary<string, Mesh>(StringComparer.Ordinal);

            foreach (var filter in root.GetComponentsInChildren<MeshFilter>(true))
            {
                if (filter == null || filter.sharedMesh == null)
                    continue;

                var source = filter.sharedMesh;
                if (source.name == null || !source.name.StartsWith(CombinedPrefix, StringComparison.Ordinal))
                    continue;

                var renderer = filter.GetComponent<MeshRenderer>();
                if (renderer == null)
                    continue;

                int first, count;
                if (!ReadBatchInfo(renderer, out first, out count) || count <= 0)
                    continue;

                if (first < 0 || first + count > source.subMeshCount)
                {
                    warnings.Add("'" + filter.name + "' points at sub-meshes " + first + "-" + (first + count - 1) +
                                 " of a combined mesh with " + source.subMeshCount + "; left as it was.");
                    continue;
                }

                try
                {
                    string key = source.GetInstanceID() + ":" + first + ":" + count + ":" +
                                 filter.transform.worldToLocalMatrix.GetHashCode();

                    Mesh mesh;
                    if (!extracted.TryGetValue(key, out mesh))
                    {
                        mesh = Extract(source, filter.transform, first, count);
                        mesh.name = filter.gameObject.name;
                        extracted[key] = mesh;
                    }

                    filter.sharedMesh = mesh;
                    ClearBatchInfo(renderer);
                    split++;
                }
                catch (Exception e)
                {
                    warnings.Add("'" + filter.name + "' could not be split out of the combined mesh: " + e.Message);
                }
            }

            return split;
        }

        private static Mesh Extract(Mesh source, Transform target, int first, int count)
        {
            var instances = new CombineInstance[count];
            var toLocal = target.worldToLocalMatrix;

            for (int i = 0; i < count; i++)
            {
                instances[i] = new CombineInstance
                {
                    mesh = source,
                    subMeshIndex = first + i,
                    transform = toLocal
                };
            }

            var mesh = new Mesh { indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };

            mesh.CombineMeshes(instances, false, true);
            mesh.RecalculateBounds();
            return mesh;
        }

        private static bool ReadBatchInfo(Renderer renderer, out int first, out int count)
        {
            first = 0;
            count = 0;

            var serialized = new SerializedObject(renderer);
            var firstProperty = serialized.FindProperty("m_StaticBatchInfo.firstSubMesh");
            var countProperty = serialized.FindProperty("m_StaticBatchInfo.subMeshCount");
            if (firstProperty == null || countProperty == null)
                return false;

            first = firstProperty.intValue;
            count = countProperty.intValue;
            return true;
        }

        private static void ClearBatchInfo(Renderer renderer)
        {
            var serialized = new SerializedObject(renderer);
            var firstProperty = serialized.FindProperty("m_StaticBatchInfo.firstSubMesh");
            var countProperty = serialized.FindProperty("m_StaticBatchInfo.subMeshCount");
            if (firstProperty == null || countProperty == null)
                return;

            firstProperty.intValue = 0;
            countProperty.intValue = 0;
            serialized.ApplyModifiedPropertiesWithoutUndo();
        }
    }
}
#endif
