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

using System.Threading.Tasks;

namespace Rokojori
{
  [Tool][GlobalClass]
  public partial class Flat_Baker:_XX_MultiBakeModeBillboardBase
  {
    [Export]
    public float yawOffset = 0;

    [Export]
    public MeshAxisSubDivider uSubDivisions;
    [Export]
    public MeshAxisSubDivider vSubDivisions;

    public override int GetNumViews()
    {
      return useDoubleSidedMaterial ? 1 : 2;
    }

    public override void CreateBakers()
    {
      var fov = multiBaker.GetCameraFOV();
      var distance = multiBaker.GetCameraDistance();
      var outputScale = multiBaker.GetOutputScale();

      var bakerCameras = multiBaker.bakerCameras;
      var mb = multiBaker;

      
      bakerCameras.ForEach(
        bk =>
        {
          var vs = bk.viewSettings;
          vs.fovDistance = Manual_BakingFDSettings.Create( fov, distance );          
          vs.rotationMode = BakingViewSettings.RotationMode.Yaw_Pitch;
        }
      );

      var mg = new MeshGeometry();  

      var numTextures = GetNumViews();
      var textureAlignment = TextureMerger.ComputeTextureAlignment( numTextures );
 
      
      var angle = yawOffset;
      

      for ( int i = 0; i < numTextures; i++ )
      {
        var index = i;

        bakerCameras[ index ].viewSettings.yaw = angle + i * 180f;
        bakerCameras[ index ].viewSettings.pitch = 0;

        var uv = TextureMerger.GetUVRectangle( textureAlignment, index, true );      
            

        var q = new MeshGeometry(); 
        var transform3D = Math3D.TRS( Vector3.Zero, bakerCameras[ index ].viewSettings.bakingRotation, Vector3.One * outputScale );
        

        var uDivisions = MeshAxisSubDivider.GetSubDivisionsU( uSubDivisions, transform3D );
        var vDivisions = MeshAxisSubDivider.GetSubDivisionsV( vSubDivisions, transform3D ); 
        
        q.AddQuadWithCustomDivisions( bakerCameras[ index ].viewSettings.bakingRotation, outputScale, uv.min, uv.max, uDivisions, vDivisions );         

        mg.Add( q );        
      
      }

      mg.ApplyTranslation( -mb.targetPivot );


      mb.X_outputMesh.Mesh = mg.GenerateMesh();  
    }

  }
}