"""Utilities for managing OmniGraph Python node registration"""
from contextlib import suppress
from pathlib import Path
from types import ModuleType

import omni.graph.tools as ogt

from .register_ogn_nodes import register_ogn_nodes


# ================================================================================
class PythonNodeRegistration:
    """Scoped object to register and deregister Python nodes as their extension is started up and shut down.
    This will be created and destroyed automatically by OmniGraph and does not need to be explicitly managed.
    """

    def __init__(self, module_to_register: ModuleType, module_name: str):
        """Save the information required to deregister the nodes when the module is shut down"""
        import_location = module_to_register.__file__
        if import_location is None:
            with suppress(AttributeError, KeyError):
                import_location = module_to_register.__path__._path[0]
        ogt.dbg_reg("Remembering registration for nodes in {} imported as {}", import_location, module_name)
        if import_location is not None:
            import_location = Path(import_location)
            if import_location.is_file():
                import_location = import_location.parent
            import_location = import_location / "ogn"
            self.__deregistration_methods = register_ogn_nodes(str(import_location), module_name)
        else:
            ogt.dbg_reg("Failed to find module location")

    def __del__(self):
        """Deregister all of the remembered nodes"""
        with suppress(AttributeError):
            for method in self.__deregistration_methods:
                ogt.dbg_reg("Calling deregistration method {}", str(method))
                method()
