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

import bpy,io
from os import listdir
from os.path import isfile, join
from s4studio.cas.blender import load_geom
from s4studio.cas.geometry import BodyGeometry
# io_sims.register()

def find_armature(context,check_proxy=False):
    """
    Searches for an armature, starting with active object, its modifiers, or first one in the scene if nothing valid is selected
    """
    ao = context.active_object
    skel = None
    if not skel and ao:

        if ao.type == 'ARMATURE':
            skel = ao
        if ao.type == 'MESH':
            for mod in ao.modifiers:
                if mod.type == 'ARMATURE' and mod.object:
                    skel = mod.object

    if not skel:
        for o in context.scene.objects:
            if o.type== 'ARMATURE':
                skel = o
    if check_proxy:
        if skel and skel.proxy and skel.proxy.type == 'ARMATURE':
            skel = skel.proxy
    return skel



#load texture
def load_material(map_name,map_resource):
    material = bpy.data.materials.new(map_name)
    texture_index= 0


    # Add base texture
    material.texture_slots.create(texture_index)
    texture_slot = material.texture_slots[texture_index]
    texture_index+=1
    texture = bpy.data.textures.new(name=map_name+'_'+material.name,type='IMAGE')
    texture_slot.texture = texture
    texture_slot.texture_coords = 'UV'
    texture.type = 'IMAGE'
    texture.image = bpy.data.textures['BaseTexture'].image
    texture_index +=1


    bpy.context.scene.render.image_settings.file_format = 'PNG'
    bpy.context.scene.render.image_settings.color_mode = 'RGBA'
    bpy.ops.image.open(filepath=map_resource)
    img = bpy.data.images.new(map_name,512,512)
    img.source = 'FILE'
    img.filepath = map_resource
    img.save_render(map_resource)
    img.filepath = map_resource


    material.texture_slots.create(texture_index)
    texture_slot = material.texture_slots[texture_index]
    texture_index+=1
    texture = bpy.data.textures.new(name=map_name+'_'+material.name,type='IMAGE')
    texture_slot.texture = texture
    texture_slot.texture_coords = 'UV'

    if map_name in ('DiffuseMap','Multiplier'):
        texture_slot.use_stencil = True
    elif map_name == 'Mask':
        texture_slot.use = False
        texture_slot.blend_type = 'OVERLAY'
        texture_slot.use_rgb_to_intensity = True
    elif map_name in ('Specular','SpecularMap','Clothing Specular'):
        texture_slot.use_map_specular = True
        texture_slot.use_map_color_spec = True
        texture_slot.use_map_hardness = True
        texture_slot.use_map_color_diffuse = False
    elif map_name == 'NormalMap':
        texture_slot.use_map_normal = True
        texture_slot.normal_factor = 0.01
        texture_slot.use_map_color_diffuse = False
    texture.type = 'IMAGE'
    texture.image = img
    return material

material= load_material('DiffuseMap', '__TEXTURE__')
geom_folder = '__GEOM__'
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','')
        print()
        geom = BodyGeometry()
        geom.read(stream)
        rig = find_armature(bpy.context)
        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

hidden_meshes=[__MESH__]
for mesh_name in hidden_meshes:
    mesh_obj = bpy.context.scene.objects[mesh_name]
    mesh_obj.hide = True
bpy.ops.wm.save_mainfile(filepath='__BLEND__')