import sys
from os import listdir
from os.path import isfile, join

from s4studio.blender import get_object_hide, set_object_hide

sys.path.append(u'__SCRIPTS__')
import io_sims
import bpy, io
from s4studio.animation.blender import *
from s4studio.cas.blender import save_geom
from s4studio.cas.geometry import BodyGeometry

geom_folder = u'__GEOM__'
i = 0
body_type = int('__BODY_TYPE__')
set_context('OBJECT', None)
for f in [geom_folder + f for f in listdir(geom_folder) if isfile(join(geom_folder, f))]:
    s = f.split('-')
    s = int(s[len(s) - 1].replace('.simgeom', ''))
    for o in get_objects():
        if o.hide_select or get_object_hide(o):
            continue
        if o.type != 'MESH':
            continue
        a = o.data.s4studio.cut
        if not a:
            continue
        cut = 0
        try:
            cut = int(a)
        except:
            print('unable to determine cut number for %s' % o)
            continue
        if cut == s:
            set_object_hide(o, False)
            mesh = o.data
            geom = BodyGeometry()
            with io.open(f, 'rb') as input_stream:
                geom.read(input_stream)
            save_geom(geom, o, body_type)
            with io.open(f, 'wb') as output_stream:
                geom.write(output_stream)
            i += 1
if i == 0:
    raise Sims4StudioException('Mesh Import Error',
                               'No meshes found to import. Make sure you set the "Cut Number" in the S4Studio Mesh Tools panel for each mesh you are importing.')
bpy.ops.wm.quit_blender()
