import logging

from fastapi import Request
from nicegui import ui

from xmas_app.components.planmigration import PlanMigration
from xmas_app.components.plantree import PlanTree
from xmas_app.pages.base import BasePage
from xmas_app.util.webchannel import connect_signal, initialize_qwebchannel

logger = logging.getLogger("xmas_app")


class PlanToolsPage(BasePage):
    """Class to encapsulate page content and methods manipulate a plan.

    Displays plans from the database in a table view and allow to load/download/delete them.
    Allows initialization of the digitalization of new plans in QGIS.
    Provides an Uploader to import GML instance files of supported appschemas.
    """

    def __init__(
        self,
        request: Request,
        plan_id: str,
    ):
        """Initializes the PlanManagerPage.

        Content is rendered via the `render()` method.

        Args:
            request: a `fastapi.Request` for e.g. header extraction
            appschema: the appschema for new plans requested by the client
            version: the appschema version for new plans requested by the client
        """
        super().__init__(request)
        self.plan_id = plan_id

    async def render(self):
        """Renders the page content."""
        await ui.context.client.connected()

        if self.client_is_qgis:
            await initialize_qwebchannel()
            await connect_signal("featureAdded")

        with ui.tabs().classes("w-full").props("no-caps dense") as tabs:
            ui.tab("tree", "Featurebaum", "schema").classes("w-full")
            ui.tab("migrate", "Versionsmigration", "upgrade").classes("w-full")

        self.tab_panels = ui.tab_panels(tabs, value="tree").classes("w-full")
        with self.tab_panels:
            with ui.tab_panel("tree"):
                await PlanTree(self.plan_id).render()
            with ui.tab_panel("migrate"):
                await PlanMigration(self.plan_id).render()
