import asyncio
from typing import Dict

from aiohttp import web
from smb.common.multiruntime.lib.io import setup_filesystem
from smb.common.sensors import BaseBuilder, HistRateBuilder

from maps_adv.common.lasagna import Lasagna
from maps_adv.geosmb.clients.bvm import BvmClient

from . import tasks
from .api import create as create_api
from .data_managers import DataManager
from .db import DB
from .domain import Domain

setup_filesystem("maps_adv/geosmb/doorman/")


class Application(Lasagna):
    SWIM_ENGINE_CLS = DB

    TASKS = {
        "geosmb_doorman__clients_yt_export": tasks.ClientsYtExportTask,
        "geosmb_doorman__call_events_import": tasks.CallEventsImportTask,
    }
    TASKS_KWARGS_KEYS = ["config", "dm", "domain"]

    SENSORS: Dict[str, BaseBuilder] = {
        **Lasagna.SENSORS,
        "empty_clients_search": HistRateBuilder().linear(size=1),
    }

    async def _setup_layers(self, db: DB) -> web.Application:
        bvm_client = await BvmClient(url=self.config["BVM_URL"])
        self.dm = DataManager(
            db=db, empty_search_sensor=self.sensors.take_group("empty_clients_search")
        )
        self.domain = Domain(self.dm, bvm_client=bvm_client)

        api = create_api(self.domain)
        api.on_shutdown.append(lambda _: asyncio.wait([bvm_client.close()]))

        return api
