# -*- coding: utf-8 -*-
# hub/ticket/ticket_plugin.py

"""Plugin-shell модуля Ticket без переноса standalone-оболочки."""

from error_logger import log_exception
from gui.containers import SContainer, VContainer

from application import TaskApplicationService
from ui import TicketShell


PLUGIN_DISPLAY_NAME = "Ticket"


class TicketPlugin(SContainer):
    """Корневая точка входа Ticket внутри общей plugin-системы."""

    def __init__(self, application_service: TaskApplicationService | None = None):
        super().__init__(width_percent=100, height_percent=100)
        self._application_service = application_service or TaskApplicationService(parent=self)
        self._shell: TicketShell | None = None
        self._is_cleaned = False
        self._setup_ui()
        self._start_application()

    def _setup_ui(self) -> None:
        """Собрать plugin-shell Ticket с локальной навигацией."""
        try:
            main_container = VContainer(margin=16, spacing=10, parent=self)
            self._shell = TicketShell(application=self._application_service, parent=self)
            main_container.add_widget(self._shell)
        except Exception as exc:
            log_exception(__name__, "TicketPlugin._setup_ui", exc)
            raise

    def _start_application(self) -> None:
        """Запустить application-слой Ticket после сборки shell."""
        try:
            self._application_service.start()
        except Exception as exc:
            log_exception(__name__, "TicketPlugin._start_application", exc)
            raise

    def cleanup(self) -> None:
        """Безопасно остановить application-слой Ticket."""
        if self._is_cleaned:
            return
        self._is_cleaned = True
        try:
            self._application_service.stop()
        except Exception as exc:
            log_exception(__name__, "TicketPlugin.cleanup", exc)

    def closeEvent(self, event) -> None:
        self.cleanup()
        super().closeEvent(event)
