import sys
from io_sims import find_armature
from s4studio.animation import ClipResourceSims4
from s4studio.animation.rig import SkeletonRig
from s4studio.blender import load_material, set_context
from s4studio.cas.blender import load_geom
from s4studio.cas.geometry import BodyGeometry

sys.path.append(u'__SCRIPTS__')

import bpy, io
from os import listdir
from os.path import isfile, join, basename
from s4studio.animation.blender import load_clip, setup_scene, load_rig

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

clip_folder = u'__CLIP__'
with io.open(clip_folder, 'rb') as stream:
    clip = ClipResourceSims4()
    clip.read(stream)
    rig = find_armature(bpy.context)
    setup_scene(rig)
    load_clip(clip, rig)

bpy.ops.wm.save_mainfile(filepath=u'__BLEND__', compress=True)
