import asyncio

from aiohttp import web
from smb.common.multiruntime.lib.io import setup_filesystem
from smb.common.pgswim import SwimEngine

from maps_adv.common.lasagna import Lasagna
from maps_adv.geosmb.doorman.client import DoormanClient

from . import api, tasks
from .data_manager import BaseDataManager, DataManager
from .db import DB
from .domain import Domain

setup_filesystem("maps_adv/geosmb/cleaner/server/")


class Application(Lasagna):
    __slots__ = ("dm", "domain")

    SWIM_ENGINE_CLS = DB
    TASKS = {"geosmb_cleaner__delete_clients": tasks.delete_clients}
    TASKS_KWARGS_KEYS = ("domain",)

    dm: BaseDataManager
    domain: Domain

    async def _setup_layers(self, db: SwimEngine) -> web.Application:
        doorman_client = await DoormanClient(
            url=self.config["DOORMAN_URL"], tvm=self.tvm, tvm_destination="doorman"
        )

        self.dm = DataManager(db)
        self.domain = Domain(
            self.dm,
            self.tvm,
            doorman_client=doorman_client,
        )

        _api = api.create(db, self.domain)

        _api.on_shutdown.append(
            lambda _: asyncio.wait([doorman_client.close()])
        )

        return _api
