from datetime import datetime

from maps_adv.stat_tasks_starter.lib.base.exceptions import UnexpectedNaiveDateTime

__select_from_source_template = """INSERT INTO {database}.{table_to} (
        ReceiveTimestamp,
        CampaignID,
        EventGroupId,
        APIKey,
        DeviceID,
        AppPlatform,
        AppVersionName,
        AppBuildNumber,
        Latitude,
        Longitude,
        EventName
    )
    SELECT
        ReceiveTimestamp,
        CampaignID,
        EventGroupId,
        APIKey,
        DeviceID,
        AppPlatform,
        AppVersionName,
        AppBuildNumber,
        Latitude,
        Longitude,
        EventName
    FROM {database}.{table_from}
    WHERE
        APIKey IN (2, 4, 30488)
        AND ReceiveTimestamp BETWEEN {timestamp_start} AND {timestamp_end}
        AND CampaignID != 0"""


def build_select_from_source(
    database: str,
    table_from: str,
    table_to: str,
    timing_from: datetime,
    timing_to: datetime,
):
    if not all([database, table_to, table_from, timing_from.tzinfo, timing_to.tzinfo]):
        raise UnexpectedNaiveDateTime()

    timestamp_from = int(timing_from.timestamp())
    timestamp_to = int(timing_to.timestamp())

    return __select_from_source_template.format(
        database=database,
        table_from=table_from,
        table_to=table_to,
        timestamp_start=timestamp_from,
        timestamp_end=timestamp_to,
    )
