import bpy
import csv


class LoadMusclesOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.load_muscle_keyframes_operator"
    bl_label = "Load muscle keyframes from file"
    filepath = bpy.props.StringProperty(subtype="FILE_PATH")

    @classmethod
    def poll(cls, context):
        return context.active_object is not None and context.active_object.type == 'MESH' and len([1 for mod in context.active_object.modifiers if mod.type == 'MUSCLE'])

    def invoke(self, context, event):
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}

    def execute(self, context):
        obj = context.active_object
        arm = obj.parent
        vs = context.active_object.data.vertices
        f = open(self.filepath, 'r')
        reader = csv.reader(f)
        header = reader.__next__()
        start_frame = context.scene.frame_current
        #should exist...
        mod = next(i for i in obj.modifiers if i.type == 'MUSCLE')
        while True:
            try:
                row = reader.__next__()
            except StopIteration:
                break
            row = dict(zip(header, row))
            context.scene.frame_current = start_frame + int(row['frame'])
            for key, val in row.items():
                if key == 'jaw':
                    arm.select = True
                    obj.select = False
                    bpy.context.scene.objects.active = arm
                    bpy.ops.object.mode_set(mode='POSE')
                    arm.pose.bones['jaw'].rotation_euler.x = float(val)
                    arm.pose.bones['jaw'].keyframe_insert(data_path="rotation_euler")
                    bpy.context.scene.objects.active = obj
                    bpy.ops.object.mode_set(mode='OBJECT')
                    obj.select = True
                    arm.select = False
                    continue
                if key != 'frame':
                    muscles = [i for i in mod.muscles if i.muscle and key == i.muscle.name]
                    if len(muscles) > 0:
                        muscle = muscles[0]
                        muscle.contraction = float(val)
                        muscle.keyframe_insert(data_path="contraction")
        f.close()
        context.scene.frame_current = start_frame
        return {'FINISHED'}