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


namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class TriangleTest:Node3D
  {  
    [Export]
    public bool alignUp = false;

    [Export]
    public bool shrink = false;
    [Export]
    public float shrinkDistance = 0;

    [Export]
    public bool scale = false;
    [Export]
    public float scaleAmount = 1;

    [ExportGroup("Source")]
    [Export]
    public Node3D sA;
    [Export]
    public Node3D sB;
    [Export]
    public Node3D sC;

    [ExportGroup("Target")]
    [Export]
    public Node3D tA;
    [Export]
    public Node3D tB;
    [Export]
    public Node3D tC;

    [Export]
    public Vector3 offset = Vector3.Zero;



    public override void _Process( double delta )
    {
      if ( alignUp )
      {
        AlignUp();
      }

      if ( shrink )
      {
        Shrink();
      }

      if ( scale )
      {
        ScaleFromCenter();
      }
    }

    void AlignUp()
    {
      var s = GetSourceTriangle();
      var r = s.GetXZAlignmentRotation();

      RJLog.Log( s.normal, r );
      
      s.Rotate( r, s.center );

      SetTargetTriangle( s );
    }

    void Shrink()
    {
      var s = GetSourceTriangle();
      s = s.Offset( shrinkDistance );

      if ( s == null )
      {
        RJLog.Log( "Shrinking failed" );
        SetTargetTriangle( GetSourceTriangle() );
        return;
      } 

      SetTargetTriangle( s );
    }

    void ScaleFromCenter()
    {
      var s = GetSourceTriangle();
      s.ScaleFromCenter( scaleAmount );

      SetTargetTriangle( s );
    }

    Triangle3 GetSourceTriangle()
    {
      return new Triangle3( sA.GlobalPosition, sB.GlobalPosition, sC.GlobalPosition );
    }

    void SetTargetTriangle( Triangle3 t )
    {
      tA.GlobalPosition = t.a + offset;
      tB.GlobalPosition = t.b + offset;
      tC.GlobalPosition = t.c + offset;
    }

  }
}
