using Godot;
using System.Collections.Generic;

public class MultiMeshHandler
{
    private readonly Dictionary<string, MultiMeshInstance3D> multiMeshes;

    public MultiMeshHandler(Dictionary<string, MultiMeshInstance3D> multiMeshes)
    {
        this.multiMeshes = multiMeshes;
    }

    public void Build(List<TileRenderData> tiles)
    {
        foreach (MultiMeshInstance3D multiMeshInstance in multiMeshes.Values)
        {
            multiMeshInstance.Multimesh.InstanceCount = 0;
        }

        Dictionary<string, List<Transform3D>> batches = new Dictionary<string, List<Transform3D>>();

        foreach (TileRenderData tile in tiles)
        {
            if (!batches.ContainsKey(tile.MeshKey))
            {
                batches[tile.MeshKey] = new List<Transform3D>();
            }

            batches[tile.MeshKey].Add(tile.Transform);
        }

        foreach (KeyValuePair<string, List<Transform3D>> kvp in batches)
        {
            MultiMesh multiMesh = multiMeshes[kvp.Key].Multimesh;
            List<Transform3D> transforms = kvp.Value;

            multiMesh.InstanceCount = transforms.Count;

            for (int i = 0; i < transforms.Count; i++)
            {
                multiMesh.SetInstanceTransform(i, transforms[i]);
            }
        }
    }
}
