# 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.
UV unwrapping and UV packing processing.
'''
__version__ = '0.1'

import logging
import math
import bpy

logger = logging.getLogger(__name__)


def uv_unwrap(obj_names, angle_limit=30):
    ''' UV unwrapping and UV packing processing '''
    for obj_name in obj_names:
        obj = bpy.data.objects[obj_name]
        bpy.ops.object.select_all(action='DESELECT')
        obj.select_set(True)
        bpy.context.view_layer.objects.active = obj
        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.select_all(action='SELECT')

        # unwrapping
        bpy.ops.uv.smart_project(angle_limit=math.radians(angle_limit))

        # packing
        bpy.ops.uv.pack_islands(udim_source='CLOSEST_UDIM',
                                rotate=True,
                                rotate_method='ANY',
                                scale=True,
                                merge_overlap=False,
                                margin_method='ADD',
                                margin=(1 / 256),
                                pin=False,
                                pin_method='LOCKED',
                                shape_method='CONCAVE')
        bpy.ops.uv.pack_islands(udim_source='CLOSEST_UDIM',
                                rotate=True,
                                rotate_method='ANY',
                                scale=True,
                                merge_overlap=False,
                                margin_method='ADD',
                                margin=(1 / 256),
                                pin=False,
                                pin_method='LOCKED',
                                shape_method='CONCAVE')

        bpy.ops.object.mode_set(mode='OBJECT')
        obj.select_set(False)

    return logger.info('UV setup of %s lowpoly meshes is finished!', len(obj_names))
