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

sys.path.append('__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
# io_sims.register()

geom_folder = '__GEOM__\\'
i = 0
for f in [geom_folder + f for f in listdir(geom_folder) if isfile(join(geom_folder, f))]:
    print('found file')
    print(f)
    s = f.split('-')
    s = s[len(s)-1].replace('.simgeom','')
    print('cut: %s'%s)
    for o in bpy.context.scene.objects:
        if o.type == 'MESH' and o.data.s4studio.s4type == 'GEOM' and o.data.s4studio.cut == s:
                print('replacing %s'%s)
                mesh = o.data
                geom = BodyGeometry()
                with io.open(f, 'rb') as input_stream:
                    geom.read(input_stream)
                save_geom(geom,o)
                with io.open(f, 'wb') as output_stream:
                    geom.write(output_stream)
                i+=1
print('replaced %s geoms' %i)
bpy.ops.wm.quit_blender()