"""Addon properties saved to the scene, not baked into preferences."""

import typing

import bpy
from bpy.props import EnumProperty
from bpy.types import Context


class RizomUVBridgeGUITabs(bpy.types.PropertyGroup):
    """Different UI tabs available to the addon."""

    names: EnumProperty(
        name="Panel Tabs",
        items=(
            ("OPERATIONS", "Operations Tab", "", "EXPORT", 0),
            ("RIZOM_LIVE", "Rizom Live Remote Tab", "", "TEXT", 1),
            ("ADDON_SETTINGS", "Addon Settings Tab", "", "PREFERENCES", 2),
        ),
    )


def get_uvmaps(self, context: Context) -> list[tuple[str, str, str]]:
    """Get UV map names from the active object.

    Returns
    -------
        list: List of Enum items for each UV map. (Identifier, Name, Description)

    """
    act_obj = context.active_object

    if not act_obj or act_obj.type != "MESH":
        return [("NO_OBJ", "INFO: No active object", "")]

    act_obj_uv_layers = act_obj.data.uv_layers
    if act_obj_uv_layers:
        items = []
        for uv_map in act_obj_uv_layers:
            name = uv_map.name
            items.append((name, name, ""))

        # This is required due to a bug with the blender API
        # https://docs.blender.org/api/master/bpy.props.html#bpy.props.EnumProperty
        RizomUVBridgeUVMaps.uv_maps_list = items
        return items

    return [("NO_MAP", "INFO: The active object has no UV Maps", "")]


def uvmap_update(self, context: Context) -> None:
    """UI update callback.

    Triggered by updating the UV map selection from the UI,
    syncs the active UV map selection with the one in the addon UI.

    """
    maps = context.window_manager.RizomUVBridgeUVMaps
    act_obj = context.active_object

    if act_obj and act_obj.type == "MESH":
        act_obj_uv_layers = act_obj.data.uv_layers
        act_obj_uv_layers.active = act_obj_uv_layers[maps.uv_maps]


class RizomUVBridgeUVMaps(bpy.types.PropertyGroup):
    """Display and set the active UV map from the addon."""

    uv_maps_list: typing.ClassVar = []
    uv_maps: EnumProperty(
        name="UV Map",
        update=uvmap_update,
        items=get_uvmaps,
    )
