import sys
from s4studio.blender import load_material, set_context, set_object_hide

sys.path.append(u'__SCRIPTS__')
from s4studio.model.geometry import Vertex
import io_sims

import bpy, io
from os import listdir
from os.path import isfile, join, basename, exists
from s4studio.cas.blender import load_geom
from s4studio.cas.geometry import BodyGeometry
from s4studio.animation.rig import SkeletonRig
from s4studio.animation.blender import load_rig

# io_sims.register()

rig_file = u'__RIG__'
if exists(rig_file):
    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)
    set_object_hide(rig, True)
    rig.hide_select = True

mannequin_folder = u'__MANNEQUIN__'
mannequin_texture_file = u'__MANNEQUIN_TEXTURE__'
if exists(mannequin_folder):
    mannequin_material = load_material('BaseTexture', mannequin_texture_file)
    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:
            splt = basename(f).split('.')
            s = splt[0]
            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
            if 'hidden' in f:
                set_object_hide(mannequin_mesh, True)

geom_folder = u'__GEOM__'
shader = u'__SHADER__'
is_cas = shader.lower() != 'simglass'
material = load_material('DiffuseMap', u'__TEXTURE__', is_cas)
i = 1
for f in [geom_folder + f for f in listdir(geom_folder) if isfile(join(geom_folder, f))]:
    with io.open(f, 'rb') as stream:
        s = f.split('-')
        s = s[len(s) - 1].replace('.simgeom', '')
        geom = BodyGeometry()
        geom.read(stream)
        mesh = load_geom('geom', geom, {}, rig, material)
        mesh.name = 's4studio_mesh_%s' % i
        mesh.data.s4studio.cut = s
        # mesh.data.s4studio.s4type = 'GEOM'
        i += 1

bpy.ops.wm.save_mainfile(filepath=bpy.data.filepath, compress=True)
