import bpy
from .. import utils

def copy_property_group(src, dst):
    for prop in src.bl_rna.properties:
        id = prop.identifier

        if id == "rna_type":
            continue

        value = getattr(src, id)

        if prop.type == 'COLLECTION':
            dst_list = getattr(dst, id)
            dst_list.clear()
            for item in value:
                new_item = dst_list.add()
                copy_property_group(item, new_item)
        elif prop.type == 'POINTER':
            if value is not None:
                setattr(dst, id, value)
            else:
                # Optional: clear pointer safely
                setattr(dst, id, None)
        elif hasattr(value, "bl_rna"):  # nested group
            copy_property_group(value, getattr(dst, id))

        else:
            setattr(dst, id, value)

class HI_PHY_OT_COPY_PARAMETER(bpy.types.Operator):
    bl_idname = "hi_phy.copy_parameter"
    bl_label = "Hi Phy Copy Parameter"
    bl_options = {'REGISTER', 'UNDO_GROUPED'}

    prototype_object: bpy.props.StringProperty(name="Prototype Object")

    def invoke(self, context, event):
        for obj in bpy.context.selected_objects:
            if utils.isSimulationObject(obj):
                self.prototype_object = obj.name
                break;
        return context.window_manager.invoke_props_dialog(self)

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

    def execute(self, context):
        src_obj = context.scene.objects[self.prototype_object]
        if not src_obj or not utils.isSimulationObject(src_obj):
            self.report({"ERROR"}, "No vavid prototype")
            return {'CANCELLED'}

        for obj in bpy.context.selected_objects:
            if obj.name != self.prototype_object:
                copy_property_group(src_obj.hi_phy, obj.hi_phy)
        return {'FINISHED'}

__CLASSES__ = [
    HI_PHY_OT_COPY_PARAMETER
]

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

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