using Godot;
using System.Collections.Generic;

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

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

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

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

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

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

        foreach (var kvp in batches)
        {
            var mm = multiMeshes[kvp.Key].Multimesh;
            var list = kvp.Value;

            mm.InstanceCount = list.Count;

            for (int i = 0; i < list.Count; i++)
                mm.SetInstanceTransform(i, list[i]);
        }
    }
}