import bpy
from mathutils import Vector
import bmesh

def NormalInDirection(normal, direction, limit = 0.99):
    return abs(direction.dot( normal )) > limit

def UpOrDown(normal):
    
    up = NormalInDirection(normal, Vector((0.0, 0.0, 1.0)), limit = 0.99)
    down = NormalInDirection(normal, Vector((0.0, 0.0, -1.0)), limit = 0.99)
    if up or down:
        return True
    return False

def generate_chord(depth, radius, location):
    
    bpy.ops.mesh.primitive_cylinder_add(radius=radius,
                                        depth=depth,
                                        location=location)
    chord = bpy.data.objects["Cylinder"]
    chord.name = "chord"
    return chord

def generate_cone_base(radius1, radius2, depth, location):

    bpy.ops.mesh.primitive_cone_add(radius1=radius1,
                                    radius2=radius2,
                                    depth=depth,
                                    location=location)
    cone = bpy.data.objects["Cone"]
    cone.name = "base"
    bpy.ops.object.mode_set(mode='EDIT')
    bm = bmesh.from_edit_mesh(cone.data)
    for face in bm.faces:
        if UpOrDown(face.normal):
            face.select = True
        else:
            face.select = False 
    faces_select = [f for f in bm.faces if f.select] 
    bmesh.ops.delete(bm, geom=faces_select, context=3)
    bmesh.update_edit_mesh(cone.data, True)
    
    # Extrude faces
    bpy.ops.mesh.select_mode( type  = 'FACE'   )
    bpy.ops.mesh.select_all( action = 'SELECT' )
    bpy.ops.mesh.extrude_region_move(
        TRANSFORM_OT_translate={"value":(0, 0, 0.01)} ) 
    bpy.ops.mesh.extrude_region_shrink_fatten(
        TRANSFORM_OT_shrink_fatten={"value":-0.05})
    bpy.ops.object.mode_set(mode='OBJECT')
    return cone
