# 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.
Generte object from collection of objects.
'''
# DEPRECATED
__version__ = '0.1'

import logging
import bpy
import math

from blender.utils.object_relations import parenting
from blender.utils.collection_tools import remove_collections_with_objects
from blender.utils.mesh_tools import collect_less_volume_objs

logger = logging.getLogger(__name__)


def hightpoly_collections_to_midpoly(collection_name, part_names, **cg_config):
    ''' Convert part's collecttions to single objects. '''
    logger.info('Midpoly objects creation launched...')
    midpoly_obj_names = []
    for part_name in part_names:
        midpoly_name = '_'.join((part_name, cg_config['midpoly']))
        midpoly_mesh = bpy.data.meshes.new(midpoly_name)
        midpoly_obj = bpy.data.objects.new(midpoly_name, midpoly_mesh)
        bpy.context.view_layer.update()
        if bpy.data.objects[part_name].parent:
            root_locator = bpy.data.objects[part_name].parent
        else:
            root_locator = bpy.data.objects[part_name]
        midpoly_obj.matrix_world = root_locator.matrix_world.copy()
        parenting(root_locator, midpoly_obj)
        midpoly_parts_col = bpy.data.collections[collection_name]
        midpoly_parts_col.objects.link(midpoly_obj)
        for col in midpoly_parts_col.children:
            # only for current part
            if part_name not in col.name:
                continue
            bpy.ops.object.select_all(action='DESELECT')
            exclude_objs = collect_less_volume_objs(col.objects, min_volume=2.0e-06)
            for obj in col.objects:
                if obj not in exclude_objs:
                    obj.select_set(state=True)
            midpoly_obj.select_set(state=True)
            bpy.context.view_layer.objects.active = midpoly_obj
            bpy.ops.object.join()
            bpy.ops.object.shade_smooth(use_auto_smooth=True)
            break
        midpoly_obj_names.append(midpoly_name)

    midpoly_parts_col.name = cg_config['midpoly_col_name']
    for col in midpoly_parts_col.children:
        remove_collections_with_objects(col)

    logger.info('Setup of %s midpoly meshes is finished!', len(part_names))
    return midpoly_obj_names
