package ru.yandex.webmaster3.worker.mirrors;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskState;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskType;
import ru.yandex.webmaster3.storage.mirrors.dao.MirrorChangeDisallowedOwnersYDao;
import ru.yandex.webmaster3.storage.util.ydb.YdbUtils;
import ru.yandex.webmaster3.storage.yql.YqlService;
import ru.yandex.webmaster3.worker.PeriodicTask;
import ru.yandex.webmaster3.worker.TaskSchedule;

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

/**
 * @author leonidrom
 */
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class ImportMirrorChangeDisallowedOwnersPeriodicTask extends PeriodicTask<PeriodicTaskState> {
    public static final String QUERY_PREFIX = "\n" +
            "PRAGMA yt.ForceInferSchema;\n" +
            "$current_timestamp = ${CURRENT_TIMESTAMP}ul;\n";

    public static final String DATA_SELECT_QUERY =
            "SELECT\n" +
            "    CAST(key as Utf8) as owner,\n" +
            "    CAST(value as Utf8) as threat,\n" +
            "    $current_timestamp as update_date\n" +
            "FROM arnold.`//home/antispam/export/mirrors/restricted_glueing`\n";

    private final MirrorChangeDisallowedOwnersYDao mirrorChangeDisallowedOwnersYDao;
    private final YqlService yqlService;

    @Value("${webmaster3.storage.ydb.dbname}")
    private String ydbDatabase;
    @Value("${webmaster3.storage.ydb.endpoint}")
    private String ydbEndpoint;

    @Override
    public Result run(UUID runId) throws Exception {
        long now = System.currentTimeMillis();
        StrSubstitutor substitutor = new StrSubstitutor(Map.of(
                "CURRENT_TIMESTAMP", String.valueOf(now)
        ));

        log.info("Table path: {}", mirrorChangeDisallowedOwnersYDao.getTablePath());
        String importQuery = substitutor.replace(QUERY_PREFIX) + YdbUtils.getImportQueryString(
                ydbEndpoint, ydbDatabase, mirrorChangeDisallowedOwnersYDao.getTablePath(), DATA_SELECT_QUERY);
        yqlService.execute(importQuery);

        //mirrorChangeDisallowedOwnersYDao.clearOldRecords(now);

        return Result.SUCCESS;
    }

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

    @Override
    public TaskSchedule getSchedule() {
        return TaskSchedule.never();
    }
}
