using Godot;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class LODMeshCreator:Node
  {
    [Export]
    public MeshInstance3D[] meshes;

    [Export]
    public float[] distances;

    [Export]
    public Mesh.PrimitiveType primitiveType = Mesh.PrimitiveType.Triangles;

    [Export]
    public bool generateTangents = true;

    [ExportToolButton("Create")]
    public Callable CreateButton => Callable.From( ()=>{ Create(); } );

    [ExportGroup("Output")]
    [Export]
    public MeshInstance3D lodMesh;

    public async Task Create()
    { 
      var list = new List<MeshGeometry>();

      var index = 0;

      foreach ( var m in meshes )
      {
        var mg = MeshGeometry.From( m.Mesh as ArrayMesh );
        mg.lodEdgeLength = distances[ index ];
        index++;

        await this.RequestNextFrame();
      }

      var mesh = MeshGeometry.GenerateLODMesh( list, primitiveType, null, generateTangents );
      
      await this.RequestNextFrame();

      this.DestroyChildren();

      await this.RequestNextFrame();

      lodMesh = this.CreateChild<MeshInstance3D>( "LODMesh" );
      lodMesh.Mesh = mesh;
      lodMesh.Mesh.SurfaceSetMaterial( 0, MaterialSurfaceContainer.GetActiveFrom( meshes[ 0 ] ) );     

    } 

  }
}