from datetime import datetime, timedelta

from aioch import Client

sql = """
INSERT INTO {database}.{accepted_table}
SELECT *, 0
FROM {database}.{normalized_table}
WHERE
    ReceiveTimestamp BETWEEN {timing_from} AND {timing_to}
    AND EventName != 'geoadv.bb.pin.show'
    AND EventGroupId IN (
        SELECT EventGroupId
        FROM {database}.{accepted_groups_table}
        WHERE ReceiveTimestamp BETWEEN {timing_from_with_delta} AND {timing_to}
    )
"""


class Collector:
    __slots__ = "config", "_client"

    config: dict
    _client: Client
    _sql_template: str = sql

    def __init__(self, **config: dict):
        self.config = config

        client_config = {
            k: config[k]
            for k in (
                "host",
                "port",
                "user",
                "password",
                "database",
                "secure",
                "ca_certs",
            )
        }
        self._client = Client(**client_config)

    def build_query(self, timing_from: datetime, timing_to: datetime) -> str:
        timing_from_with_delta = timing_from - timedelta(seconds=self.config["lag"])

        return self._sql_template.format(
            database=self.config["database"],
            accepted_table=self.config["accepted_table"],
            normalized_table=self.config["normalized_table"],
            timing_from=int(timing_from.timestamp()),
            timing_to=int(timing_to.timestamp()),
            accepted_groups_table=self.config["accepted_groups_table"],
            timing_from_with_delta=max(int(timing_from_with_delta.timestamp()), 0),
        )

    async def __call__(self, timing_from: datetime, timing_to: datetime):
        query = self.build_query(timing_from, timing_to)
        await self._client.execute(query)
