package ru.yandex.webmaster3.worker.memorandum;

import java.util.Map;

import lombok.Setter;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.joda.time.DateTime;
import org.joda.time.Instant;

import ru.yandex.webmaster3.core.worker.task.PeriodicTaskType;
import ru.yandex.webmaster3.storage.searchurl.MemorandumStatsYDao;
import ru.yandex.webmaster3.storage.util.ydb.YdbYqlService;
import ru.yandex.webmaster3.storage.util.yt.YtCypressService;
import ru.yandex.webmaster3.storage.util.yt.YtException;
import ru.yandex.webmaster3.worker.TaskSchedule;

/**
 * @author avhaliullin
 */
public class MdbImportMemorandumInfoTask extends ImportMemorandumInfoTask {

    private static final String QUERY_PREFIX = "\n" +
            "PRAGMA yt.ForceInferSchema;\n" +
            "pragma yt.ExternalTx='${TRANSACTION_ID}';\n" +
            "$current_timestamp = ${CURRENT_TIMESTAMP}ul;\n" +
            "$update_date = DateTime::FromMilliseconds(cast($current_timestamp as Uint64));\n";

    private static final String DATA_SELECT_QUERY =  "SELECT \n" +
            "            cast(HostId as Utf8) as host_id,\n" +
            "            cast($update_date as Timestamp) as last_update,\n" +
            "            cast(`Count` as UInt64) as banned_urls\n" +
            "        FROM ${SOURCE_TABLE}";

    @Setter
    private MemorandumStatsYDao memorandumStatsYDao;
    @Setter
    private YdbYqlService ydbYqlService;

    @Override
    protected void importMemorandumStats(YtCypressService cypressService, Instant tableDate) throws YtException {
        DateTime now = DateTime.now();
        StrSubstitutor substitutor = new StrSubstitutor(Map.of(
                "CURRENT_TIMESTAMP", String.valueOf(now.getMillis()),
                "SOURCE_TABLE", makeTablePath(tableDate, MemorandumYtTableType.STATS).toYqlPath(),
                "TRANSACTION_ID", cypressService.getTransactionId()
        ));
        ydbYqlService.importToYdb(memorandumStatsYDao.getTablePath(), substitutor.replace(DATA_SELECT_QUERY), substitutor.replace(QUERY_PREFIX));
        memorandumStatsYDao.clearOldRecords(now);
    }

    @Override
    public PeriodicTaskType getType() {
        return PeriodicTaskType.MDB_IMPORT_MEMORANDUM_DATA;
    }

    @Override
    public TaskSchedule getSchedule() {
        return TaskSchedule.startByCron("40 55 * * * *");
    }

}
