# 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 os, sys

import maya.cmds as cmds
import maya.OpenMayaMPx as OpenMayaMPx

GLTF_TRANSLATOR_NAME = 'Verge3D glTF'
HTML_TRANSLATOR_NAME = 'HTML'
VENDOR = 'Soft8Soft'
VERSION = '4.13.0'

class V3DGLTFTranslator(OpenMayaMPx.MPxFileTranslator):
    def __init__(self):
        OpenMayaMPx.MPxFileTranslator.__init__(self)
    def haveWriteMethod(self):
        return True
    def haveReadMethod(self):
        return False
    def filter(self):
        return '*.gltf'
    def defaultExtension(self):
        return 'gltf'

    def writer(self, fileObj, optStr, accessMode):

        import const
        import pluginUtils
        log = pluginUtils.log.getLogger('V3D-MY')

        if const.V3D_PLUGIN_NAME not in cmds.pluginInfo(query=True, listPlugins=True):
            log.error('Verge3D GLTF Exporter requires Verge3D plugin to be loaded.')
            return

        fullName = fileObj.fullName()
        try:
            if accessMode in [OpenMayaMPx.MPxFileTranslator.kExportAccessMode,
                              OpenMayaMPx.MPxFileTranslator.kExportActiveAccessMode]:
                import interface
                interface.exportGLTFPath(fileObj.fullName(), False,
                                         accessMode == OpenMayaMPx.MPxFileTranslator.kExportActiveAccessMode)
        except:
            log.error('Failed to write file information')
            raise

    def reader(self, fileObject, optionString, accessMode):
        raise NotImplementedError()

    def identifyFile(self, fileObj, buffer, size):
        basename, ext = os.path.splitext(fileObj.fullName())

        if ext in ['.gltf', '.glb']:
            return self.kIsMyFileType
        else:
            return self.kNotMyFileType

def gltfTranslatorCreator():
    return OpenMayaMPx.asMPxPtr(V3DGLTFTranslator())

class V3DHTMLTranslator(OpenMayaMPx.MPxFileTranslator):
    def __init__(self):
        OpenMayaMPx.MPxFileTranslator.__init__(self)
    def haveWriteMethod(self):
        return True
    def haveReadMethod(self):
        return False
    def filter(self):
        return '*.html'
    def defaultExtension(self):
        return 'html'

    def writer(self, fileObj, optStr, accessMode):

        import const
        import pluginUtils
        log = pluginUtils.log.getLogger('V3D-MY')

        if const.V3D_PLUGIN_NAME not in cmds.pluginInfo(query=True, listPlugins=True):
            log.error('HTML exporter requires Verge3D plugin to be loaded.')
            return

        fullName = fileObj.fullName()
        try:
            if accessMode in [OpenMayaMPx.MPxFileTranslator.kExportAccessMode,
                              OpenMayaMPx.MPxFileTranslator.kExportActiveAccessMode]:
                import interface
                interface.exportGLTFPath(fileObj.fullName(), False,
                                         accessMode == OpenMayaMPx.MPxFileTranslator.kExportActiveAccessMode)
        except:
            log.error('Failed to write file information')
            raise

    def reader(self, fileObject, optionString, accessMode):
        raise NotImplementedError()

    def identifyFile(self, fileObj, buffer, size):
        basename, ext = os.path.splitext(fileObj.fullName())

        if ext in ['.html']:
            return self.kIsMyFileType
        else:
            return self.kNotMyFileType

def htmlTranslatorCreator():
    return OpenMayaMPx.asMPxPtr(V3DHTMLTranslator())

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

    sys.path.append(os.path.normpath(os.path.join(mpluginPath, 'lib')))
    sys.path.append(os.path.normpath(os.path.join(mpluginPath, '..', 'python')))
    import pluginUtils
    log = pluginUtils.log.getLogger('V3D-MY')

    try:
        mplugin.registerFileTranslator(HTML_TRANSLATOR_NAME, None, htmlTranslatorCreator)
    except:
        log.error('Failed to register translator: {}'.format(HTML_TRANSLATOR_NAME))
        raise

    try:
        mplugin.registerFileTranslator(GLTF_TRANSLATOR_NAME, None, gltfTranslatorCreator)
    except:
        log.error('Failed to register translator: {}'.format(GLTF_TRANSLATOR_NAME))
        raise

def uninitializePlugin(mobject):
    mplugin = OpenMayaMPx.MFnPlugin(mobject)

    import pluginUtils
    log = pluginUtils.log.getLogger('V3D-MY')

    try:
        mplugin.deregisterFileTranslator(HTML_TRANSLATOR_NAME)
    except:
        log.error('Failed to unregister translator: {}'.format(HTML_TRANSLATOR_NAME))
        raise

    try:
        mplugin.deregisterFileTranslator(GLTF_TRANSLATOR_NAME)
    except:
        log.error('Failed to unregister translator: {}'.format(GLTF_TRANSLATOR_NAME))
        raise
