from datetime import datetime
from decimal import Decimal
from typing import List

from maps_adv.stat_tasks_starter.lib.base import BaseClickhousePoint

from . import query_builders as query_builders


class EventsPoint(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)

    def prepare_select_events_sql(
        self,
        campaign_id: int,
        event_cost: Decimal,
        timing_from: datetime,
        timing_to: datetime,
        limit: int,
        limit_offset: int,
    ):
        return query_builders.build_select_events(
            database=self.database,
            table=self.normalized_table,
            campaign_id=campaign_id,
            event_cost=event_cost,
            timing_from=timing_from,
            timing_to=timing_to,
            limit=limit,
            limit_offset=limit_offset,
        )

    async def __call__(self, select_sqls: List[str]):
        insert_sql = query_builders.build_insert(
            self.database, self.charged_table, select_sqls
        )
        await self.client.execute(insert_sql)

    async def check_charging_withing_period(
        self, timing_from: datetime, timing_to: datetime
    ) -> bool:
        check_charges_sql = query_builders.build_existing_charged_events(
            self.database, self.charged_table, timing_from, timing_to
        )
        charged_in_period = await self.client.execute(check_charges_sql)

        return bool(charged_in_period)
