import bpy
import io
import os
import s4studio
import sys
from io_sims import find_armature, Sims4StudioException
from os.path import exists
from s4studio.animation.blender import save_clip

sys.path.append(u'__SCRIPTS__')
skeleton = find_armature(bpy.context)
if not skeleton:
    raise Sims4StudioException('Clip Import Error',
                               'Please make sure that the .blend file that you are importing has a rig.')

if not skeleton.animation_data:
    raise Sims4StudioException('Clip Import Error',
                               'Please make sure that you have set a key frame on the rig in your .blend file.')
action = skeleton.animation_data.action
filepath = u'__CLIP__'
clip_resource = s4studio.animation.ClipResourceSims4()
with io.open(u'__CLIP__', 'rb') as clip_stream:
    clip_resource.read(clip_stream)
clip_resource.clip.frame_duration = 1.0 / 30.0
save_clip(clip_resource, skeleton, True)
clip_resource.duration = clip_resource.clip.max_frame_count / 30.0
with io.open(filepath, 'wb') as output_stream:
    clip_resource.write(output_stream)
bpy.ops.wm.quit_blender()
