# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import bpy

from bpy.types import Operator
from bpy.props import FloatProperty, StringProperty


class UI_OT_support_quick_uv_unwrap(Operator):
    """
    Quick and simple UV unwrap, currently used for AOE maps.
    """
    bl_idname = 'snw.support_quick_uv_unwrap'
    bl_label = 'Unwrap'
    bl_description = 'Quick unwrap of active object'
    bl_options = {'REGISTER'}


    uv_set: StringProperty() # type: ignore
    margin: FloatProperty() # type: ignore


    def execute(self, context):
        o = context.active_object # type: bpy.types.Object
        if self.uv_set not in o.data.uv_layers:
            o.data.uv_layers.new(name=self.uv_set)
        o.data.uv_layers[self.uv_set].active = True

        #old_mode = context.mode

        bpy.ops.object.mode_set(mode='OBJECT')
        selected = context.selected_objects
        [ o.select_set(False) for o in selected ]

        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.uv.smart_project(
            angle_limit=1.15192, 
            island_margin=self.margin, 
            area_weight=0.0, 
            correct_aspect=True, 
            scale_to_bounds=False
        )

        bpy.ops.object.mode_set(mode='OBJECT')
        [ o.select_set(True) for o in selected ]

        #bpy.ops.object.mode_set(mode=old_mode)
        
        return {'FINISHED'}