from datetime import datetime
from typing import Tuple

from maps_adv.stat_tasks_starter.lib.base import BaseClickhousePoint
from maps_adv.stat_tasks_starter.lib.charger.collector.query_builders import (
    build_select_events_stat,
    build_union_select_events,
)


class Collector(BaseClickhousePoint):
    def __init__(self, normalized_table: str, charged_table: str, **kwargs):
        self.database = kwargs["database"]
        self.normalized_table = normalized_table
        self.charged_table = charged_table
        super().__init__(**kwargs)

    async def __call__(
        self, timing_from: datetime, timing_to: datetime, timezone_campaigns: dict
    ) -> Tuple[Tuple[int, int, int, int]]:
        events_selects = [
            build_select_events_stat(
                self.database,
                self.normalized_table,
                self.charged_table,
                timing_from,
                timing_to,
                campaigns_ids,
                tz_name,
            )
            for tz_name, campaigns_ids in timezone_campaigns.items()
        ]

        full_sql = build_union_select_events(events_selects)

        return await self.client.execute(full_sql)
