from aiohttp import web

from smb.common.multiruntime.lib.io import setup_filesystem

from maps_adv.warden.client.lib import PeriodicalTask, TaskMaster

from . import api, task_executor
from .config import config
from .db import db

setup_filesystem("maps_adv/adv_store/")


class Application:
    api: web.Application = None
    task_master: TaskMaster = None

    async def setup(self, path=None):
        config.init(path)
        self.api = api.create()
        self._setup_tasks()
        await db.setup(config.DATABASE_URI, config.DATABASE_URI_RO)

    def _setup_tasks(self):
        executor_classes = [
            getattr(task_executor, name) for name in config.TASKS_TO_START
        ]
        if not executor_classes:
            return

        tasks_to_start = [
            PeriodicalTask(executor_class.task_type, executor_class.do_run)
            for executor_class in executor_classes
        ]

        self.task_master = TaskMaster(
            server_url=config.WARDEN_API_URL, tasks=tasks_to_start
        )

        self.api.on_startup.append(self._start_tasks)
        self.api.on_shutdown.append(self._stop_tasks)

    async def _start_tasks(self, _):
        await self.task_master.run()

    async def _stop_tasks(self, _):
        await self.task_master.stop()
