"""Implementation of the extension containing the Test Runner window."""
import logging
import sys

import carb
import omni.ext
from omni.kit.ui import EditorMenu

# Cannot do relative imports here due to the way the omni.kit.window import space is duplicated in multiple extensions
from omni.kit.window._test_runner_window import _LOG
from omni.kit.window._test_runner_window import TestRunnerWindow


# ==============================================================================================================
class Extension(omni.ext.IExt):
    """The extension manager that handles the life span of the test runner window"""
    def __init__(self):
        self._test_runner_window = None
        self._menu_item = None
        super().__init__()

    def _show_window(self, menu: str, value: bool):
        if self._test_runner_window is None:
            self._test_runner_window = TestRunnerWindow(value)
        else:
            self._test_runner_window.visible = value

    def on_startup(self):
        _LOG.disabled = True  # Set to False to dump out debugging information for the extension
        if not _LOG.disabled:
            _handler = logging.StreamHandler(sys.stdout)
            _handler.setFormatter(logging.Formatter("TestRunner: %(levelname)s: %(message)s"))
            _LOG.addHandler(_handler)
            _LOG.setLevel(logging.INFO)
        _LOG.info("Starting up the test runner extension")
        open_window = carb.settings.get_settings().get("/exts/omni.kit.window.tests/openWindow")
        self._menu_item = EditorMenu.add_item(TestRunnerWindow.MENU_PATH, self._show_window, toggle=True, value=open_window)
        if open_window:
            self._show_window(TestRunnerWindow.MENU_PATH, True)

    def on_shutdown(self):
        """Cleanup the constructed elements"""
        _LOG.info("Shutting down the test runner extension")
        if self._test_runner_window is not None:
            _LOG.info("Destroying the test runner window")
            self._test_runner_window.visible = False
            self._test_runner_window.destroy()
            self._test_runner_window = None
            EditorMenu.remove_item(TestRunnerWindow.MENU_PATH)
        handler_list = _LOG.handlers
        for handler in handler_list:
            _LOG.removeHandler(handler)

        self._menu_item = None
