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

class HI_PHY_OT_CreatePointConstraint(bpy.types.Operator):
    bl_idname = "hi_phy.create_point_constraint"
    bl_label = "Hi Phy Create Point Constraint"
    bl_options = {'REGISTER', 'UNDO_GROUPED'}
    
    def execute(self, context):
        depsgraph = bpy.context.evaluated_depsgraph_get()
        # evaluate it so we can get the correct topology after modifiers
        obj = bpy.context.active_object.evaluated_get(depsgraph);
        selected_indices = getSelectedPoints(obj, self)
        if not selected_indices:
            return {'CANCELLED'}
        # we can't get position attributes from mesh unless we are in object mode
        bpy.ops.object.mode_set(mode='OBJECT')
        if not create_point_constraint.createPointConstraintObject(obj, selected_indices, obj.name + "_point_constraint", self):
            bpy.ops.object.mode_set(mode='EDIT')
            return {'CANCELLED'}
        bpy.ops.object.mode_set(mode='EDIT')
        return {'FINISHED'}

__CLASSES__ = [
    HI_PHY_OT_CreatePointConstraint
]

# Define the menu draw function
def menu_draw(self, context):
    # TODO: only add to the menu if the edited object is a valid simulation object
    layout = self.layout
    layout.operator("hi_phy.create_point_constraint")

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

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