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



namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class ConnectionCircle:Node3D
  #if TOOLS 
 , GizmoDrawer
#endif
  {
    [Export]
    public bool updateAlways = false;

    [Export]
    public Node3D root;

    [Export]
    public float radius = 1;
    float _radius = -1;

    [Export( PropertyHint.Range, "2,64") ]
    public int divisions = 16;
    int _divisions = -1;

    [Export]
    public float editorGizmoSize = 1;

    float _editorGizmoSize = 1;

    public Pose GetLocalPose( int index )
    {
      var p = new Pose();
      var state = index / (float)( divisions );
      var radians = state * Mathf.Pi * 2f;
      var angle = Mathf.RadToDeg( radians );

      p.rotation = Quaternion.FromEuler( new Vector3( 0, -radians , 0 ) );
      p.position = p.rotation * Vector3.Forward * radius;

      // RJLog.Log( radians, angle, p.rotation, p.position );

      return p;
    }

    public Pose GetGlobalPose( int index )
    {
      return GetLocalPose( index ).ToGlobal( this );
    }

#if TOOLS

   
    public void DrawGizmo( EditorNode3DGizmoPlugin gizmoPlugin, EditorNode3DGizmo gizmo )
    {
      gizmo.Clear();
      

      var material = gizmoPlugin.GetMaterial( "main", gizmo );

      for ( int i = 0; i < divisions; i++ )
      {
        var p = GetLocalPose( i );

        var center  = p.position;
        var up      = p.position + p.up * editorGizmoSize;
        var forward = p.position + p.forward * editorGizmoSize;
        var right   = p.position + p.right * radius * 4f / divisions;
        var left    = p.position - p.right * radius * 4f / divisions;

        /*gizmo.AddLines( new Vector3[] 
          {
            center, forward
          },
          material
        );*/

        gizmo.AddLines( new Vector3[] 
          {
            center, up, 
            center, forward,
            right, left,
            right, forward,
            left, forward,
            up, forward

          },
          material
        );
        
      }


    }

    public override void _Process( double delta )
    {
      var changed = false;

      if ( editorGizmoSize != _editorGizmoSize || 
           radius != _radius ||
           divisions != _divisions
      )
      {
        _editorGizmoSize = editorGizmoSize;
        _radius = radius;
        _divisions = divisions;

        changed = true;
      }

      if ( changed )
      {
        UpdateGizmos();
      }

      

    }


#endif
   
  }
}