from .. import utils
import bpy

class HI_PHY_OT_AddBaseNormal(bpy.types.Operator):
    bl_idname = "hi_phy.add_base_normal"
    bl_label = "Hi Phy Add Base Normal"
    bl_options = {'REGISTER', 'UNDO_GROUPED'}

    simulation_curves: bpy.props.StringProperty(name="Simulation Curves")

    base_normal: bpy.props.FloatVectorProperty(
            default=(0.0005, 1 - 0.001, 0.0005),
            name="Base normal: ",
            precision=5
    )

    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.simulation_curves = obj.name
        return context.window_manager.invoke_props_dialog(self)

    def draw(self, context):
        layout = self.layout
        layout.prop(self, "simulation_curves")
        layout.prop(self, "base_normal")

    def execute(self, context):
        sim_obj = bpy.data.objects[self.simulation_curves]
        if sim_obj.type != 'CURVES':
            self.report({"ERROR"}, "We can only create base normals for curves")
            return {'CANCELLED'}            
        n_curves = sim_obj.data.attributes.domain_size('CURVE')
        if "hi_phy_base_normal" in sim_obj.data.attributes:
            self.report({"WARNING"}, "Base normal already exists, remove and start over")
            sim_obj.data.attributes.remove(sim_obj.data.attributes["hi_phy_base_normal"])
        base_normal_attr = sim_obj.data.attributes.new("hi_phy_base_normal", 'FLOAT_VECTOR', 'CURVE')
        v = [v for i in range(n_curves) for v in self.base_normal]
        base_normal_attr.data.foreach_set('vector', v);
        return {'FINISHED'}

__CLASSES__ = [
    HI_PHY_OT_AddBaseNormal
]

def menu_draw(self, context):
    # TODO: only add to the menu if the edited object is a valid simulation object
    layout = self.layout
    layout.separator()
    layout.operator_context = 'INVOKE_DEFAULT'
    layout.operator("hi_phy.add_base_normal")

def register():
    for class_ in __CLASSES__:
        bpy.utils.register_class(class_)
        bpy.types.VIEW3D_MT_object_context_menu.append(menu_draw)


def unregister():
    for class_ in reversed(__CLASSES__):
        bpy.types.VIEW3D_MT_object_context_menu.remove(menu_draw)
        bpy.utils.unregister_class(class_)
