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

import java.util.Objects;
import java.util.stream.Collectors;

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.ImportColumnDefinition;
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 25/09/2020.
 */
@Value
@AllArgsConstructor(onConstructor_ = @JsonCreator)
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public class ImportPreprocessRenameColumns implements ImportPreprocessPolicy {

    String intermediateTableName;

    @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());
        // генерируем запрос для переименования колонок
        YqlQueryBuilder builder = new YqlQueryBuilder();
        StrSubstitutor substitutor = context.createSubstitutor(builder);
        builder.cluster(task.getSourceTable());
        builder.transaction(context.getCypressService().getTransactionId());
        builder.appendText("\n");
        builder.appendText("INSERT INTO").appendTable(intermediateTable).appendText("WITH TRUNCATE\n");
        builder.appendText("SELECT\n");
        builder.appendText(context.getDefinition().getColumns().stream().map(ImportColumnDefinition::asYqlExpression)
                .map(substitutor::replace).collect(Collectors.joining(",\n"))
        );
        builder.appendText("\n").appendText("FROM").appendTable(task.getSourceTable()).appendText(";\n");

        context.getYqlService().execute(builder.build());
        return task.updateStage(task.getNextStage()).intermediateTable(intermediateTable).build();
    }

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