package ru.yandex.webmaster3.storage.importer.model.preprocess;

import java.util.Objects;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;
import org.apache.commons.lang3.text.StrSubstitutor;

import ru.yandex.webmaster3.storage.importer.model.ImportContext;
import ru.yandex.webmaster3.storage.importer.model.ImportTask;
import ru.yandex.webmaster3.storage.util.yt.YtPath;
import ru.yandex.webmaster3.storage.yql.YqlQueryBuilder;

/**
 * Created by Oleg Bazdyrev on 01/10/2020.
 * Выполняет указанный YQL-запрос в качестве подготовки. Знает о некоторых подстановках
 */
@Value
@AllArgsConstructor(onConstructor_ = @JsonCreator)
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public class ImportPreprocessYqlQuery implements ImportPreprocessPolicy {

    String yqlQuery;
    String intermediateTableName;

    @Override
    public ImportPreprocessType getType() {
        return ImportPreprocessType.YQL_QUERY;
    }

    @Override
    public ImportTask apply(ImportContext context) {
        ImportTask task = context.getTask();
        YtPath intermediateTable = YtPath.create(task.getSourceTable().getCluster(),
                YtPath.path(context.getWorkDir(), Objects.requireNonNullElse(intermediateTableName, context.getDefinition().getId()))
                        .getPathWithoutCluster());
        // refresh task/context
        task = task.toBuilder().intermediateTable(intermediateTable).build();
        context = context.toBuilder().task(task).build();
        YqlQueryBuilder queryBuilder = new YqlQueryBuilder();
        StrSubstitutor substitutor = context.createSubstitutor(queryBuilder);
        String resultQuery = substitutor.replace(yqlQuery);
        queryBuilder.appendText(resultQuery);
        context.getYqlService().execute(queryBuilder.build());
        return task.withNextStage().build();
    }

}
