import bpy


def main(context):
    print("start copy")
    for ob in context.scene.objects:
        #check for proxy_smname custom property
        if "proxy_smname" in ob:
            smname = ob["proxy_smname"]
            src_obj = bpy.data.objects.get(smname)
            if src_obj is None:
                continue
            print("found object")
            bpy.ops.object.select_all(action='DESELECT')
            bpy.ops.object.select_pattern(pattern=smname)
            bpy.context.scene.objects.active = bpy.context.selected_objects[0]
            #remove ue4proxy_ prefix
            actualname = ob.name[9:len(ob.name)]
            print(ob.name," ",actualname," ", bpy.context.selected_objects[0])
            
            #don't copy if scene mesh name is same as staticmesh name
            if actualname == smname:
                new_obj = src_obj
            else:
                new_obj = src_obj.copy()
                new_obj.data = src_obj.data.copy()
                new_obj.name = actualname
                context.scene.objects.link(new_obj)
            
            #copy transforms
            new_obj.location = ob.location
            new_obj.rotation_euler = ob.rotation_euler
            new_obj.scale = ob.scale
            
    print("start delete t3d proxies")
    bpy.ops.object.select_all(action='DESELECT')
    for ob in context.scene.objects:
        #check for proxy_smname custom property
        if "proxy_smname" in ob:
            smname = ob["proxy_smname"]
            src_obj = bpy.data.objects.get(smname)
            if src_obj is None:
                continue
            print("found object")
            
            ob.select = True
    
    bpy.ops.object.delete()

            #bpy.context.scene.objects.active = ob
    #on fbx import object is selected but not active
    #bpy.context.scene.objects.active = bpy.context.selected_objects[0] 
    #bpy.context.active_object.active_material.diffuse_color = (0.25, 0.24, 0.23)
    #bpy.context.active_object['smname'] = bpy.context.active_object.name



class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    @classmethod
    def poll(cls, context):
        return context.active_object is not None

    def execute(self, context):
        main(context)
        return {'FINISHED'}


def register():
    bpy.utils.register_class(SimpleOperator)


def unregister():
    bpy.utils.unregister_class(SimpleOperator)


if __name__ == "__main__":
    register()

    # test call
    bpy.ops.object.simple_operator()
