import bpy


default_material: bpy.types.Material = None

def findDefaultMaterial():
    global default_material
    if default_material is not None:
        return default_material
    # iterate materials and try to find one that matches the default material name
    for material in bpy.data.materials:
        if material.name == "NEEDLE_Default_Material":
            default_material = material
            return default_material
    if default_material is None:
        # create default material
        default_material = bpy.data.materials.new(name="NEEDLE_Default_Material")
    return default_material


class NEEDLE_OT_assign_default_material(bpy.types.Operator):
    bl_idname = "needle.assign_default_material"
    bl_label = "Assign Default Material"

    afterExecuteLambda = None
    
    def execute(self, context):
        assignedMaterials = 0
        for obj in context.selected_objects:
            if obj.type == "MESH":
                if obj.active_material is None:
                    assignedMaterials += 1
                    obj.active_material = findDefaultMaterial()     
        if(assignedMaterials > 0):
            self.report({'INFO'}, "Assigned default material to " + str(assignedMaterials) + " objects")
            if self.afterExecuteLambda is not None:
                self.afterExecuteLambda()
        return {'FINISHED'}