import math
import os
import sys
from s4studio.blender import set_context, rotate_obj

sys.path.append(u'__SCRIPTS__')
import bpy, io
from s4studio.buybuild.blender import load_lod
from s4studio.buybuild.geometry import ModelLod
from s4studio.animation.rig import SkeletonRig
from s4studio.animation.blender import load_rig

geometry_state = u'__STATE__'
state_hash = None if geometry_state == u'' else int(geometry_state)

mlod_file = u'__MLOD__'
rig_file = u'__RIG__'
armature = None
if os.path.exists(rig_file):
    rig_resource = SkeletonRig()
    with io.open(rig_file, 'rb') as rig_stream:
        rig_resource.read(rig_stream)

    print(rig_resource)
    print([bone.name for bone in rig_resource.bones])
    set_context('OBJECT')
    armature = load_rig(rig_resource)
    set_context('OBJECT', armature)
    rotate_obj(math.pi, 'Z')
    bpy.ops.object.transform_apply(rotation=True)

dir = os.path.dirname(os.path.abspath(mlod_file))
with io.open(mlod_file, 'rb') as mlod_stream:
    mlod = ModelLod()
    mlod.read(mlod_stream)
    mesh = load_lod(armature, mlod, dir, state_hash)
bpy.ops.file.autopack_toggle()
bpy.ops.wm.save_mainfile(filepath=bpy.data.filepath, compress=True)
