# Shelf button + menu installer for RFX_GLTF_Exporter.
# No f-strings. ASCII only.
#
# RFX convention: every tool lives under one shared top-level Maya menu named
# "Reimagine Fx Tools". install_menu() is non-destructive: it creates that
# menu only if it does not already exist, and replaces only this plugin's own
# menu item, so sibling RFX tools that use the same menu name are preserved.

from maya import cmds, mel

from .. import settings


_SHELF_BUTTON_LABEL = "RFXglTF"

# Shared across all RFX tools -- do not rename per plugin.
_MENU_NAME = "reimagineFxToolsMenu"
_MENU_LABEL = "Reimagine Fx Tools"
_MENU_ITEM = "rfxGltfExporterMenuItem"

_LAUNCH_CMD = (
    "import RFX_GLTF_Exporter\n"
    "import importlib\n"
    "importlib.reload(RFX_GLTF_Exporter)\n"
    "RFX_GLTF_Exporter.launch()"
)


def _current_shelf():
    try:
        top = mel.eval("$tmpVar=$gShelfTopLevel")
        return cmds.tabLayout(top, query=True, selectTab=True)
    except Exception:
        return None


def install_shelf_button(shelf=None):
    shelf = shelf or _current_shelf()
    if not shelf:
        cmds.warning("RFX_GLTF_Exporter: no active shelf to install to.")
        return False
    existing = cmds.shelfLayout(shelf, query=True, childArray=True) or []
    for btn in existing:
        try:
            if cmds.shelfButton(btn, query=True, label=True) == _SHELF_BUTTON_LABEL:
                cmds.deleteUI(btn)
        except Exception:
            pass
    cmds.shelfButton(
        parent=shelf,
        label=_SHELF_BUTTON_LABEL,
        annotation=settings.PLUGIN_LABEL,
        image1=settings.icon_path().replace("\\", "/"),
        imageOverlayLabel="",
        style="iconOnly",
        marginWidth=0,
        marginHeight=1,
        overlayLabelBackColor=(0.0, 0.0, 0.0, 0.0),
        command=_LAUNCH_CMD,
        sourceType="python",
    )
    return True


def install_menu():
    main_window = mel.eval("$tmpVar=$gMainWindow")
    # Create the shared "Reimagine Fx Tools" menu only if it is not already
    # present (another RFX tool may have created it this session).
    try:
        if not cmds.menu(_MENU_NAME, exists=True):
            cmds.menu(_MENU_NAME, parent=main_window, label=_MENU_LABEL, tearOff=True)
    except Exception:
        cmds.menu(_MENU_NAME, parent=main_window, label=_MENU_LABEL, tearOff=True)
    # Replace only this plugin's own item so sibling tools survive.
    try:
        if cmds.menuItem(_MENU_ITEM, exists=True):
            cmds.deleteUI(_MENU_ITEM)
    except Exception:
        pass
    cmds.menuItem(_MENU_ITEM, parent=_MENU_NAME, label=settings.PLUGIN_LABEL,
                  command=_LAUNCH_CMD)
    return True
