#!/usr/bin/python

import os
import bpy

def bl_clear_scene():
    bpy.ops.object.select_all(action='TOGGLE')
    bpy.ops.object.select_all(action='TOGGLE')
    bpy.ops.object.delete(use_global=False)


def convert_dae_to_stl(collada_filename):
    bl_clear_scene()
    
    #Load the model
    bpy.ops.wm.collada_import(filepath=collada_filename, import_units=False, fix_orientation=False)  #FIXME: Check these options
    
    # #Select the model
    # bpy.ops.object.select_all(action='TOGGLE')
    # bpy.ops.object.select_all(action='TOGGLE')

    # #Some of the objects don't have the rotation applied, and the dimensions are in the wrong axes
    # #bpy.ops.object.transform_apply(rotation=True)
    # #Better apply scale, just in case
    bpy.ops.object.transform_apply(rotation=True, scale=True)
    bpy.ops.export_mesh.stl(filepath=collada_filename[:-4]+'.stl')

    # bpy.ops.object.select_all(action='TOGGLE')
    # bpy.ops.object.select_by_type(type='MESH')
    
    # if (len(bpy.context.selected_objects) > 1) :
    #     print("[WARNING] More than one mesh in the file. Taking the first one.")

    # d = bpy.context.selected_objects[0].dimensions

# traverse root directory, and list directories as dirs and files as files
cwd = os.getcwd()
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    # print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        if file.endswith('.dae'):
            print(cwd+root+file)
            convert_dae_to_stl(cwd+'/'+root[1:]+'/'+file)
