"""Maya plugin entry point: OpenPose_full renderer (Maya API 2.0).

Registers, in order:
  * the ``openposeCharacter`` mapping node (mapping_node.py)
  * its Viewport 2.0 draw override, the live skeleton overlay (draw_override.py)
  * the ``openposeCreateCharacter`` / ``openposeShowMappingEditor`` commands
    and the mapping editor UI (commands.py, ui/mapping_editor.py)
  * the "OpenPose" viewport renderer + ``openposeRenderSequence`` command
    (render_override.py)

See ../README.md for install and usage instructions.

Note: the ``python/`` package directory is added to sys.path using
MFnPlugin.loadPath() inside initializePlugin(), not module-level __file__ --
Maya's plugin loader does not reliably set __file__ when it execs a .py
plugin, so the package import is deferred until loadPath() is available.
"""

import os
import sys

import maya.api.OpenMaya as om

maya_useNewAPI = True

VENDOR = "OpenPose Renderer Plugin"
VERSION = "1.0.0"

# Populated by _import_submodules() once the plugin's own directory is known.
_MODULES = []


def _import_submodules(fn_plugin):
    python_dir = os.path.normpath(os.path.join(fn_plugin.loadPath(), "..", "python"))
    if python_dir not in sys.path:
        sys.path.insert(0, python_dir)

    from openpose_renderer import mapping_node
    from openpose_renderer import draw_override
    from openpose_renderer import commands
    from openpose_renderer import render_override

    return [mapping_node, draw_override, commands, render_override]


def initializePlugin(m_object):
    fn_plugin = om.MFnPlugin(m_object, VENDOR, VERSION, "Any")

    global _MODULES
    _MODULES = _import_submodules(fn_plugin)

    for module in _MODULES:
        try:
            module.register(fn_plugin)
        except Exception as error:
            om.MGlobal.displayError(
                "openposeRenderer: failed to register {0}: {1}".format(module.__name__, error)
            )
            raise


def uninitializePlugin(m_object):
    fn_plugin = om.MFnPlugin(m_object)

    errors = []
    for module in reversed(_MODULES):
        try:
            module.deregister(fn_plugin)
        except Exception as error:
            errors.append("{0}: {1}".format(module.__name__, error))

    if errors:
        message = "openposeRenderer: errors during uninitialize -- " + "; ".join(errors)
        om.MGlobal.displayError(message)
        raise RuntimeError(message)
