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.clients.bvm import BvmClient
from maps_adv.geosmb.clients.cdp import CdpClient
from maps_adv.geosmb.clients.geosearch import GeoSearchClient

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

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


class Application(Lasagna):
    SWIM_ENGINE_CLS = DB

    TASKS = {
        "geosmb_marksman__cdp_users_sync_task": tasks.CdpUsersSyncTask,
        "geosmb_marksman__sync_segment_sizes": tasks.sync_segments_sizes,
    }
    TASKS_KWARGS_KEYS = ("config", "domain", "dm")

    async def _setup_layers(self, db: SwimEngine) -> web.Application:
        self.dm = DataManager(db)

        bvm = self.register_client(await BvmClient(self.config["BVM_URL"]))
        geosearch = self.register_client(
            await GeoSearchClient(
                url=self.config["GEOSEARCH_URL"],
                tvm=self.tvm,
                tvm_destination="geosearch",
            )
        )
        cdp = self.register_client(
            await CdpClient(self.config["CDP_URL"], tvm=self.tvm, tvm_destination="cdp")
        )

        self.domain = Domain(dm=self.dm, bvm=bvm, geosearch=geosearch, cdp=cdp)

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

        return _api
