"""Operator for automatically unwrapping objects."""

from typing import Callable

import bpy
from bpy.types import Context, Event

from rizomuvbridge_ultimate import constants
from rizomuvbridge_ultimate.functions.bpy_funcs.get_prefs import get_addon_prefs


class RizomAutomatic(bpy.types.Operator):
    """Use RizomUV to automatically unwrap selected objects.

    Just a composition operator which combines other manual commands.

    """

    bl_description = "Automatically use RizomUV autoseams to generate UV maps"
    bl_idname = "ruv.rizom_automatic"
    bl_label = "Automatic (RizomUV)"
    bl_options = {"REGISTER", "INTERNAL"}

    @classmethod
    def poll(cls, context: Context) -> bool:
        """Check if there is an active mesh object.

        Returns
        -------
            True if there is an active mesh object

        """
        return context.active_object is not None and context.active_object.type == "MESH"

    def execute(self, context: Context) -> set[str]:
        """Execute the operator."""
        prefs = get_addon_prefs()
        if prefs.export_actions not in constants.AUTOSEAMS_ENUMS.keys():
            self.report({"ERROR"}, "Must select an autoseams export action")
            return {"CANCELLED"}

        bpy.ops.ruv.rizom_export()
        bpy.ops.ruv.rizom_import()
        bpy.ops.ruv.rizom_action(action="CLOSE")

        return {"FINISHED"}

    def invoke(self, context: Context, event: Event) -> Callable:
        """Run before execution of the operator.

        Used to enable a confirmation dialog before execution.

        Returns
        -------
            Confirmation dialog or execute the operator.

        """
        prefs = get_addon_prefs()

        if prefs.confirm_export:
            return context.window_manager.invoke_confirm(
                self,
                event,
                title="Confirm Export",
                message=f"This will overwrite the existing RizomUV {prefs.export_format} file",
            )

        return self.execute(context)
