import logging
import tempfile
from asyncio.futures import Future

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
from .config import config
from .pipeline.base import export as export_pipeline

setup_filesystem("maps/doc/", "")

logger = logging.getLogger(__name__)


class Application:
    api: web.Application = None
    export_runner: Future = None
    cache_folder: tempfile.TemporaryDirectory = None

    async def setup(self, path=None):
        config.init(path)

        self.api = api.create()

        self._setup_tasks()

    def _setup_tasks(self):
        self._task_master = TaskMaster(
            server_url=config.WARDEN_URL,
            tasks=[PeriodicalTask("export_campaigns", self._export_task)],
        )

        self.api.on_startup.append(self._init_cache)
        self.api.on_startup.append(self._start_export_runner)

        self.api.on_cleanup.append(self._stop_export_runner)
        self.api.on_cleanup.append(self._clean_cache)

    async def _export_task(self, _):
        await export_pipeline(config, self.cache_folder.name)

    async def _init_cache(self, _):
        self.cache_folder = tempfile.TemporaryDirectory()

    async def _clean_cache(self, _):
        if self.cache_folder:
            self.cache_folder.cleanup()

    async def _start_export_runner(self, _):
        await self._task_master.run()

    async def _stop_export_runner(self, _):
        await self._task_master.stop()
