#  ***** BEGIN GPL LICENSE BLOCK *****
#
#   Copyright (C) 2024 Ilia Kurochkin <brothermechanic@yandex.com>
#
#   Created by Ilia Kurochkin (brothermechanic)
#   contact:    brothermechanic@yandex.com
#
#   This 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.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, see <https://www.gnu.org/licenses/>.
#
#  ***** END GPL LICENSE BLOCK *****
#
# coding: utf-8
'''
DESCRIPTION.
Decorator for export functions.
'''

import os
import bpy
import mathutils


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('file_dir', '//')
        kwargs.setdefault('sub_dir', '')
        kwargs.setdefault('reset_transforms', False)

        if kwargs['reset_transforms']:
            obj = bpy.data.objects.get(kwargs['obj_name'])
            obj.name = kwargs['obj_name'] + '_orig'
            obj_data = obj.data.copy()
            obj_tmp = obj.copy()
            obj_tmp.data = obj_data
            obj_tmp.name = kwargs['obj_name']
            bpy.context.collection.objects.link(obj_tmp)
            obj_tmp.parent = None
            obj_tmp.matrix_world = mathutils.Matrix()

        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
        file_dir = os.path.join(kwargs['file_dir'], kwargs['sub_dir'])
        os.makedirs(file_dir, exist_ok=True)
        kwargs['outpath'] = os.path.join(file_dir, kwargs['obj_name'])
        # return export function
        file_path = func(**kwargs)

        #cleanup temporary object
        if kwargs['reset_transforms']:
            bpy.data.objects.remove(obj, do_unlink=True)
            obj = bpy.data.objects.get(kwargs['obj_name'] + '_orig')
            obj.name = kwargs['obj_name']

        return file_path

    return wrapper
