package ru.yandex.webmaster3.worker.recommendedquery;

import java.util.Map;
import java.util.UUID;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.worker.task.PeriodicTaskState;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskType;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.storage.recommendedquery.dao.DomainsWithDirectDynamicAdsYDao;
import ru.yandex.webmaster3.storage.util.ydb.YdbYqlService;
import ru.yandex.webmaster3.storage.util.yt.YtPath;
import ru.yandex.webmaster3.storage.yql.YqlFunctions;
import ru.yandex.webmaster3.worker.PeriodicTask;
import ru.yandex.webmaster3.worker.TaskSchedule;

/**
 * @author avhaliullin
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ImportDomainsWithDirectDynAdsTask extends PeriodicTask<PeriodicTaskState> {

    public static final String QUERY_PREFIX = "\n" +
            "PRAGMA yt.ForceInferSchema;\n" +
            "$current_timestamp = ${CURRENT_TIMESTAMP}ul;\n" +
            "$update_date = DateTime::FromMilliseconds(cast($current_timestamp as Uint64));\n" +
            YqlFunctions.CUT_WWW_AND_M.getFunctionDef() + "\n";

    public static final String DATA_SELECT_QUERY =  "SELECT \n" +
            "            cast(Domain as Utf8) as domain,\n" +
            "            cast($update_date as Timestamp) as last_update\n" +
            "        FROM ${SOURCE_TABLE}";

    private final DomainsWithDirectDynamicAdsYDao domainsWithDirectDynamicAdsYDao;
    private final YdbYqlService ydbYqlService;
    @Value("${webmaster3.worker.direct.domains-with-dyn-ads.tablePath}")
    private YtPath directDomainsPath;

    @Override
    public Result run(UUID runId) throws Exception {
        DateTime now = DateTime.now();
        StrSubstitutor substitutor = new StrSubstitutor(Map.of(
                "CURRENT_TIMESTAMP", String.valueOf(now.getMillis()),
                "SOURCE_TABLE", directDomainsPath.toYqlPath()
        ));

        ydbYqlService.importToYdb(domainsWithDirectDynamicAdsYDao.getTablePath(), substitutor.replace(DATA_SELECT_QUERY), substitutor.replace(QUERY_PREFIX));
        domainsWithDirectDynamicAdsYDao.clearOldRecords(now);
        return new Result(TaskResult.SUCCESS);
    }

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

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

}
