#!bpy
"""
Name: 'Generator for bracelts'
Blender: 2.7x
Group: 'Generators'
Tooltip: 'Creat a basic shape for a bracelet'
"""
import bpy
   
def create_objects(x=0, y=0, z=0, anz=20):

   for i in range(anz):
      bpy.ops.mesh.primitive_uv_sphere_add(size=1,
                                           segments=64,
                                           ring_count=32,
                                           view_align=False, 
                                           enter_editmode=False, 
                                           location=(i*1.4, y, z+2))
      # maybe more flat...
      # bpy.ops.transform.resize(value=(0.65, 0.65, 0.65),
      #                         constraint_axis=(False, False, True))
def deg_to_rad(d):
    import math
    return d * math.pi / 180.0
      
def glue_all():
   scn = bpy.context.scene
   teil = scn.objects['Sphere']
   scn.objects.active = teil
   for i, sphere in enumerate(bpy.data.objects):
      if i == 0:
         continue
      boolean = teil.modifiers.new('SphereBoolean', 'BOOLEAN')
      boolean.object = sphere
      boolean.operation = 'UNION'
      bpy.ops.object.modifier_apply(apply_as='DATA', modifier='SphereBoolean')
      bpy.context.scene.objects.unlink(sphere)


def bend_object_add():
   rx = deg_to_rad(90)
   ry = deg_to_rad(-180)
   rz = deg_to_rad(-90)
   
   bpy.ops.object.empty_add(
      type='ARROWS',
      radius=1,
      view_align=False,
      location=(0, 0, 0),
      rotation=(rx, ry, rz)
   )
   return

def bend():
   scn = bpy.context.scene
   teil = scn.objects['Sphere']
   scn.objects.active = teil
   bpy.ops.object.modifier_add(type='SIMPLE_DEFORM')
   bpy.context.object.modifiers["SimpleDeform"].deform_method = 'BEND'
   bpy.context.object.modifiers["SimpleDeform"].angle = deg_to_rad(350)
   bpy.ops.object.modifier_apply(apply_as='DATA', modifier="SimpleDeform")

def delete_all():
    for item in bpy.context.scene.objects:
        bpy.context.scene.objects.unlink(item)

    for item in bpy.data.objects:
        bpy.data.objects.remove(item)

    for item in bpy.data.meshes:
        bpy.data.meshes.remove(item)

    for item in bpy.data.materials:
        bpy.data.materials.remove(item)

if __name__ == "__main__":
   delete_all()
   # first ring
   create_objects(1,3,1,40)
   # second ring
   create_objects(1,3,2,40)
   # third ring
   create_objects(1,3,3,40)
   
   glue_all()
   bend_object_add()
   bend()