# -*- coding: utf-8 -*-
"""
DESCRIPTION.
STL mesh exporter.
Exports all objects in scene.
You can set export path and subdir.
"""
__version__ = "0.1"

import logging
import sys
import bpy
import os

logger = logging.getLogger(__name__)


def export_col_stl(path, subdir=""):
    """ STL mesh exporter. Exports all objects in scene. """
    for ob in bpy.context.scene.objects:
        # deselect all but just one object and make it active
        bpy.ops.object.select_all(action='DESELECT')
        ob.select_set(state=True)
        bpy.context.view_layer.objects.active = ob
        filename = bpy.context.active_object.name
        # create collision hull mesh
        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.convex_hull()
        bpy.ops.object.mode_set(mode='OBJECT')
        bpy.ops.object.modifier_add(type='DECIMATE')
        bpy.context.object.modifiers["Decimate"].ratio = 0.2

        # export stl
        stl_path = os.path.join(path, subdir).replace('\\', '/')
        if not os.path.isdir(stl_path):
            os.makedirs(stl_path)
        outpath = os.path.join(stl_path, filename+'.stl')
        logger.debug('collision:', outpath)

        bpy.ops.export_mesh.stl(filepath=outpath, check_existing=False, filter_glob='*.stl', use_selection=True, global_scale=1.0, use_scene_unit=False, ascii=False, use_mesh_modifiers=True, batch_mode='OFF', axis_forward='Y', axis_up='Z')
