import bpy
import io
from io_sims import find_armature
from os import listdir
from os.path import isfile, basename
from os.path import join
from s4studio.animation.blender import setup_scene, load_rig
from s4studio.animation.rig import SkeletonRig
from s4studio.blender import set_context, load_material
from s4studio.cas.blender import load_geom
from s4studio.cas.geometry import BodyGeometry

rig_file = u'__RIG__'
rig_resource = SkeletonRig()
with io.open(rig_file, 'rb') as rig_stream:
    rig_resource.read(rig_stream)
set_context('OBJECT')
rig = load_rig(rig_resource, is_cas=True)

mannequin_material = load_material('BaseTexture', u'__MANNEQUIN_TEXTURE__')
mannequin_folder = u'__MANNEQUIN__'
for f in [mannequin_folder + f for f in listdir(mannequin_folder) if isfile(join(mannequin_folder, f))]:
    with io.open(f, 'rb') as stream:
        s = basename(f).replace('.simgeom', '')
        geom = BodyGeometry()
        geom.read(stream)
        mannequin_mesh = load_geom('geom', geom, {}, rig, mannequin_material)
        mannequin_mesh.name = s
        mannequin_mesh.parent = rig
        mannequin_mesh.hide_select = True

setup_scene(rig)
set_context('POSE', rig)
bpy.context.scene.frame_end = int('__DURATION__')
bpy.ops.wm.save_mainfile(filepath=u'__BLEND__', compress=True)
