import bpy
import bmesh
import os
from ..cAPI import SimulationAPI
from .. import utils
from ..utils import update_duo_sphere
import numpy as np

class HI_PHY_OT_CreateGrabConstraint(bpy.types.Operator):
    bl_idname = "hi_phy.create_grab_constraint"
    bl_label = "Hi Phy Create Grab Constraint"
    bl_options = {'REGISTER', 'UNDO_GROUPED'}

    inner_radius: bpy.props.FloatProperty(name="Inner Radius", default = 0.05)
    outer_radius: bpy.props.FloatProperty(name="Outer Radius", default = 0.10)
    center: bpy.props.FloatVectorProperty(name="Center")

    def invoke(self, context, event):
        self.center = bpy.context.scene.cursor.location
        return context.window_manager.invoke_props_dialog(self)

    def draw(self, context):
        layout = self.layout
        layout.prop(self, "inner_radius")
        layout.prop(self, "outer_radius")
        layout.prop(self, "center")
            
    def execute(self, context):
        # Create an object
        mesh = bpy.data.meshes.new("grab_constraint")
        obj = bpy.data.objects.new("grab_constraint", mesh)
        obj.hi_phy.is_active = True
        obj.hi_phy.object_type = "CONSTRAINT"
        obj.hi_phy.constraint_type = SimulationAPI.ConstraintType.GrabConstraint
        # constraint object is not used for grab constraint, we just use something so we can export
        obj.hi_phy.constraint_object0 = obj
        obj.hi_phy.constraint_object1 = obj
        obj.location = self.center
        # set outer first, set inner radius first will prevent it to be set as the outer is still 0
        obj.hi_phy.grab_constraint_outer_radius = self.outer_radius
        obj.hi_phy.grab_constraint_inner_radius = self.inner_radius
        bpy.context.collection.objects.link(obj)        
        return {'FINISHED'}

__CLASSES__ = [
    HI_PHY_OT_CreateGrabConstraint
]

def register():
    for class_ in __CLASSES__:
        bpy.utils.register_class(class_)

def unregister():
    for class_ in reversed(__CLASSES__):
        bpy.utils.unregister_class(class_)
