package ru.yandex.webmaster3.worker.turbo.commerce;

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.storage.turbo.dao.commerce.TurboMarketFeedsYDao;
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;

/**
 * Created by Oleg Bazdyrev on 10/12/2020.
 * Импорт маркетных фидов
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ImportTurboMarketFeedsTask 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($CutWWWM(Url::GetHost(host))._2 as Utf8) as domain,\n" +
                    "            cast(feed_url as Utf8) as feed_url,\n" +
                    "            cast(feed_id as Utf8) as feed_id,\n" +
                    "            cast(is_feed_enabled as Bool) as is_feed_enabled,\n" +
                    "            cast(datasource_id as Utf8) as datasource_id,\n" +
                    "            cast(datasource_name as Utf8) as datasource_name,\n" +
                    "            cast(campaign_id as Utf8) as campaign_id,\n" +
                    "            cast($update_date as Timestamp) as update_date\n" +
                    "        FROM ${SOURCE_TABLE}";

    private final YdbYqlService ydbYqlService;
    private final TurboMarketFeedsYDao turboMarketFeedsYDao;

    @Value("${webmaster3.worker.turbo.marketFeeds.sourceTable.path}")
    private YtPath sourceTable;

    @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", sourceTable.toYqlPath()
        ));

        ydbYqlService.importToYdb(turboMarketFeedsYDao.getTablePath(), substitutor.replace(DATA_SELECT_QUERY), substitutor.replace(QUERY_PREFIX));
        turboMarketFeedsYDao.clearOldRecords(now);

        return Result.SUCCESS;
    }

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

    @Override
    public TaskSchedule getSchedule() {
        return TaskSchedule.startByCron("0 18 */6 * * *");
    }
}
