# Copyright (c) 2017-2026 Soft8Soft, LLC. All rights reserved.
#
# Use of this software is subject to the terms of the Verge3D license
# agreement provided at the time of installation or download, or which
# otherwise accompanies this software in either electronic or hard copy form.
import importlib, logging, os, sys

import maya.api.OpenMaya as om
import maya.cmds as cmds
import maya.mel as mel

VENDOR = 'Soft8Soft'
VERSION = '4.13.0'
V3D_SETTINGS_NAME = 'v3dSettings'

def maya_useNewAPI():
    pass

class V3DSettings(om.MPxNode):

    def __init__(self):
        om.MPxNode.__init__(self)

def nodeCreator():
    return V3DSettings()

def nodeInitializer():
    import customAttrs
    customAttrs.initSettingsNode(V3D_SETTINGS_NAME)

def devReloadModules():
    mods = [
        'pluginUtils.convert',
        'pluginUtils.gltf',
        'pluginUtils.log',
        'pluginUtils.manager',
        'pluginUtils.math',
        'pluginUtils.path',
        'pluginUtils.rawdata',
        'pluginUtils',
        'matNodes',
        'mayaUtils',
        'const',
        'customAttrs',
        'customShelf',
        'collect',
        'export',
        'interface',
        'reflectionCubemap',
        'reflectionCubemapTpl',
        'reflectionPlane',
        'reflectionPlaneTpl',
        'clippingPlane',
        'clippingPlaneTpl'
    ]

    for name in mods:
        if name in sys.modules:
            importlib.reload(sys.modules[name])

def onBeforeUnload(*args):
    import customAttrs
    customAttrs.removeSettingsNode()

    cmds.flushUndo()

def initializePlugin(mobject):
    mplugin = om.MFnPlugin(mobject, VENDOR, VERSION, 'Any')
    mpluginPath = mplugin.loadPath()

    sys.path.append(os.path.normpath(os.path.join(mpluginPath, 'lib')))
    sys.path.append(os.path.normpath(os.path.join(mpluginPath, 'lib', 'customNodes')))
    sys.path.append(os.path.normpath(os.path.join(mpluginPath, '..', 'python')))

    import const
    import pluginUtils as pU
    log = pU.log.getLogger('V3D-MY')
    log.info('Initialize Verge3D plugin')

    if pU.debug:
        devReloadModules()

    """
    NOTE: using OpenMaya.MFnPlugin.setName() in Maya 2022 Python API 2.0 causes
    crashes. If not specified the default name equals to "verge3d" (matches the
    plugin's file name).
    """

    try:
        mplugin.registerNode(V3D_SETTINGS_NAME, const.V3D_SETTINGS_ID,
                nodeCreator, nodeInitializer)
    except:
        log.error('Failed to register node: {}'.format(V3D_SETTINGS_NAME))
        raise

    logging.getLogger('tornado.access').disabled = True

    from pluginUtils.manager import AppManagerConn
    from pluginUtils.path import getRoot

    AppManagerConn.init(getRoot(), 'MAYA')

    if not AppManagerConn.ping():
        AppManagerConn.start()

    import interface
    interface.initRuntimeCommands(mpluginPath)
    interface.createMenu()

    import customAttrs

    customAttrs.assignNodeSettings()

    def depPluginLoadCb(*args, **kwargs):
        name = args[0][1]
        if name == 'mtoa' or name == 'mayaUsdPlugin':
            customAttrs.assignNodeSettings()
    om.MSceneMessage.addStringArrayCallback(om.MSceneMessage.kAfterPluginLoad, depPluginLoadCb)

    cmds.scriptJob(event=('SceneOpened', customAttrs.assignNodeSettings))

    om.MSceneMessage.addStringArrayCallback(om.MSceneMessage.kBeforePluginUnload, onBeforeUnload)

    cmds.callbacks(addCallback=interface.customAttrEditorUI, hook='AETemplateCustomContent', owner=mplugin.name)

    import customShelf
    customShelf.registerShelf(mpluginPath)

    import reflectionCubemap
    reflectionCubemap.register(mplugin)

    import reflectionPlane
    reflectionPlane.register(mplugin)

    import clippingPlane
    clippingPlane.register(mplugin)

def uninitializePlugin(mobject):

    import pluginUtils as pU
    log = pU.log.getLogger('V3D-MY')
    log.info('Unloading Verge3D plugin')

    import interface
    interface.removeMenu()

    import const
    mplugin = om.MFnPlugin(mobject)
    try:
        mplugin.deregisterNode(const.V3D_SETTINGS_ID)
    except:
        log.error('Failed to unregister node: {}'.format(V3D_SETTINGS_NAME))
        raise

    import reflectionCubemap
    reflectionCubemap.unregister(mplugin)

    import reflectionPlane
    reflectionPlane.unregister(mplugin)

    import clippingPlane
    clippingPlane.unregister(mplugin)
