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

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

    binding_simulation_object: bpy.props.StringProperty(name="Binding Simulation Object")
    binding_mesh: bpy.props.StringProperty(name="Binding Mesh")
    def invoke(self, context, event):
        for obj in bpy.context.selected_objects:
            if utils.isSimulationObject(obj) and obj.hi_phy.object_type == "ELASTIC_ROD":
                self.binding_simulation_object = obj.name
            else:
                self.binding_mesh = obj.name
        return context.window_manager.invoke_props_dialog(self)

    def draw(self, context):
        layout = self.layout
        layout.prop(self, "binding_simulation_object")
        layout.prop(self, "binding_mesh")

    def execute(self, context):
        depsgraph = bpy.context.evaluated_depsgraph_get()
        # evaluate it so we can get the correct topology after modifiers
        sim_obj = bpy.data.objects[self.binding_simulation_object].evaluated_get(depsgraph)
        mesh_obj = bpy.data.objects[self.binding_mesh].evaluated_get(depsgraph)
        # we can't get position attributes from mesh unless we are in object mode
        bk_mode = bpy.context.object.mode
        bpy.ops.object.mode_set(mode='OBJECT')
        if not create_root_constraint.create(sim_obj, mesh_obj, sim_obj.name + "_to_" + mesh_obj.name + "_root_constraint", self):
            bpy.ops.object.mode_set(mode=bk_mode)
            return {'CANCELLED'}
        bpy.ops.object.mode_set(mode=bk_mode)
        return {'FINISHED'}

__CLASSES__ = [
    HI_PHY_OT_CreateRootConstraint
]

# 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_context = 'INVOKE_DEFAULT'
    layout.operator("hi_phy.create_root_constraint")

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


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