from datetime import datetime

from maps_adv.stat_controller.client.lib.normalizer import TaskStatus
from maps_adv.stat_tasks_starter.lib.base.pipeline import BasePipeline
from maps_adv.stat_tasks_starter.lib.config import config

from .shift_data import DataShifter


class Pipeline(BasePipeline):
    __slots__ = "normalize_data_config"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.normalize_data_config = {
            "table_from": config.CH_STORAGE_SOURCE_TABLE,
            "table_to": config.CH_STORAGE_NORMALIZED_TABLE,
            "database": config.CH_STORAGE_DB,
            "host": config.CH_STORAGE_HOST,
            "port": config.CH_STORAGE_PORT,
            "user": config.CH_STORAGE_USER,
            "password": config.CH_STORAGE_PASSWORD,
        }
        if config.CH_STORAGE_USE_SSL:
            self.normalize_data_config["secure"] = True
            self.normalize_data_config["ca_certs"] = config.SSL_CERT_FILE

    async def __call__(self):
        new_task_data = await self.find_new_task()
        task_id = new_task_data["id"]

        await self.normalize_data(
            task_id=task_id,
            timing_from=new_task_data["timing_from"],
            timing_to=new_task_data["timing_to"],
        )

    async def find_new_task(self) -> dict:
        return await self._stat_client.find_new_task(executor_id=self.executor_id)

    async def normalize_data(
        self, task_id: int, timing_from: datetime, timing_to: datetime
    ):
        data_to_normalize = DataShifter(**self.normalize_data_config)
        await data_to_normalize(timing_from=timing_from, timing_to=timing_to)

        await self._stat_client.update_task(
            task_id=task_id, status=TaskStatus.completed, executor_id=self.executor_id
        )
