using System.Collections;
using System.Collections.Generic;
using Godot;
using System;



namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class QuadBillboardsFromMesh:QuadBillboardDataProcessor
  { 
    [Export]
    public float density = 1;

    [Export]
    public MeshInstance3D source;

    [Export]
    public bool updateMesh = false;

    MeshGeometry _cached = null;

    public override List<QuadBillboardData> Process( List<QuadBillboardData> data )
    {
      if ( source == null || source.Mesh == null )
      {
        _cached = null;
        return data;
      }

      if ( _cached == null || updateMesh )
      {
        _cached = MeshGeometry.From( source );
      }

      var parent = GetParent<QuadBillboardMeshGenerator>();

      var tri = new Triangle3( Vector3.Zero, Vector3.One, Vector3.One * 2 );

      _cached.ForEachTriangle(
        ( t, a, b, c  )=>
        {
          var tri = Triangle3.CreateFrom( _cached, t );
          tri = tri.Shrink( density / 2f );

          if ( tri == null )
          {
            return;
          }

          var normal = tri.normal;

          var outline = tri.GetOutline();

          var length = outline.ComputeLength(-1);

          while ( outline != null && outline.ComputeLength(0) > density )
          {
            var numPoints = Mathf.Ceil( length / density );

            for ( int i = 0; i < numPoints; i++ )
            {
              var s = (float)i / ( numPoints );
              var p = outline.PositionAt( s );
            }

            tri = tri.Shrink( density );

            if ( tri == null )
            {
              outline =null;
            }
            else
            {
              outline = tri.GetOutline();
            }          
            
          }
        }
      );

      var d = new QuadBillboardData();
      d.position = GlobalPosition - parent.GlobalPosition;
      d.rotation = this.GlobalQuaternion();
      d.scale    = Scale;
      d.visible = true;

      data.Add( d );
      return data;
    }
  }
}