# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
'''
DESCRIPTION.
Decorator for export functions.
'''
import logging
import os
import bpy
import mathutils

logger = logging.getLogger(__name__)


def export_decorator(func):

    def wrapper(**kwargs):
        bpy.ops.object.select_all(action='DESELECT')
        # add defaults
        kwargs.setdefault('global_scale', 1000)
        kwargs.setdefault('axis_forward', 'Y')
        kwargs.setdefault('axis_up', 'Z')
        kwargs.setdefault('path', '//')
        kwargs.setdefault('subdir', '')

        obj = bpy.data.objects.get(kwargs['obj_name'])
        # deselect all but just one object and make it active
        bpy.ops.object.select_all(action='DESELECT')
        obj.select_set(state=True)
        bpy.context.view_layer.objects.active = obj
        # clean hierarchy and transforms
        obj.parent = None
        # reset transforms
        obj.matrix_world = mathutils.Matrix()
        # construct path
        filename = bpy.context.active_object.name
        filepath = os.path.join(kwargs['path'],
                                kwargs['subdir']).replace('\\', '/')
        if not os.path.isdir(filepath):
            os.makedirs(filepath)
        # store path
        kwargs['outpath'] = os.path.join(filepath, filename)
        # return export function
        return func(**kwargs)

    return wrapper
