import os
import re
import bpy

class HI_PHY_ERROR_OT_Report(bpy.types.Operator):
    bl_idname = "hi_phy.error_report"
    bl_label = "Error Reporter"

    message: bpy.props.StringProperty()

    def execute(self, context):
        self.report({'ERROR'}, self.message)
        return {'FINISHED'}

class HI_PHY_LIST_OT_AddItem(bpy.types.Operator):
    bl_idname = "hi_phy.add_item_to_list"
    bl_label = "Add Item"

    list_prop: bpy.props.StringProperty()
    index_prop: bpy.props.StringProperty()

    def execute(self, context):
        collection = getattr(context.object.hi_phy, self.list_prop)
        index = getattr(context.object.hi_phy, self.index_prop)

        # Add item
        collection.add()

        # Set index to last
        setattr(context.object.hi_phy, self.index_prop, len(collection) - 1)
        return {'FINISHED'}


class HI_PHY_LIST_OT_RemoveItem(bpy.types.Operator):
    bl_idname = "hi_phy.remove_item_from_list"
    bl_label = "Remove Item"

    list_prop: bpy.props.StringProperty()
    index_prop: bpy.props.StringProperty()

    def execute(self, context):
        collection = getattr(context.object.hi_phy, self.list_prop)
        index = getattr(context.object.hi_phy, self.index_prop)

        if 0 <= index < len(collection):
            collection.remove(index)

        # Clamp index
        new_index = min(index, len(collection) - 1)
        setattr(context.object.hi_phy, self.index_prop, new_index)
        return {'FINISHED'}

class HI_PHY_OT_Add(bpy.types.Operator):
    bl_idname = "hi_phy.add"
    bl_label = "Add Hi Phy object"
    bl_options = {'REGISTER'}

    def execute(self, context):
        obj = context.object
        obj.hi_phy.is_active = True        
        return {'FINISHED'}


class HI_PHY_OT_Remove(bpy.types.Operator):
    bl_idname = "hi_phy.remove"
    bl_label = "Remove Hi Phy object"
    bl_options = {'REGISTER'}

    def execute(self, context):
        obj = context.object
        obj.hi_phy.is_active = False
        obj.hi_phy.object_type = 'NONE'
        return {'FINISHED'}

__CLASSES__ = [
    HI_PHY_ERROR_OT_Report,
    HI_PHY_OT_Add,
    HI_PHY_OT_Remove,
    HI_PHY_LIST_OT_AddItem,
    HI_PHY_LIST_OT_RemoveItem
]


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


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