package ru.yandex.webmaster3.worker.mirrors;

import java.util.Objects;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import ru.yandex.webmaster3.storage.jupiter.JupiterUtils;
import ru.yandex.webmaster3.storage.util.yt.YtNode;
import ru.yandex.webmaster3.storage.util.yt.YtPath;
import ru.yandex.webmaster3.storage.ytimport.YtClickhouseDataLoad;
import ru.yandex.webmaster3.storage.ytimport.YtClickhouseDataLoadState;
import ru.yandex.webmaster3.worker.turbo.AbstractYqlPrepareImportTask;


@Slf4j
public abstract class AbstractImportJupiterExportTask extends AbstractYqlPrepareImportTask {

    @Autowired
    protected JupiterUtils jupiterUtils;

    @Override
    protected YtClickhouseDataLoad init(YtClickhouseDataLoad latestImport) throws Exception {
        return ytService.inTransaction(tablePath).query(cypressService -> {
            @NonNull String baseState = getBaseState();

            final YtPath priemkaExportTablePath = getPathToTableInExport(baseState, getJupiterSuffix());

            final YtNode node = cypressService.getNode(priemkaExportTablePath);
            final String lastBaseState = Objects.requireNonNullElse(latestImport.getData(), "");
            baseState = JupiterUtils.getStateWithOnlyDigits(baseState);
            if (node != null && !baseState.equals(lastBaseState)) {
                final LocalDate date = node.getUpdateTime().toLocalDate();

                log.info("previously base state -- {}, current base state -- {}", lastBaseState, baseState);

                return latestImport.withData(baseState)
                        .withSourceTable(priemkaExportTablePath, date, date);
            }
            // ничего нового
            return latestImport.withState(YtClickhouseDataLoadState.DONE);
        });
    }

    @Override
    @Value("${webmaster3.worker.jupiter.baseMeta.ytPath}")
    public void setTablePath(YtPath tablePath) {
        super.setTablePath(tablePath);
    }

    protected YtPath getPathToTableInExport(String baseState, String suffix) {
        return YtPath.path(YtPath.path(tablePath, "export/" + baseState), suffix);
    }

    // //home/jupiter/export/yyyyMMdd-HHmmss  возвращать часть суффикса после версии экспорта, например /mirrors/mirrors
    protected abstract String getJupiterSuffix();

    // /home/jupiter/export/{}/...  возвращать номер базы, yyyyMMdd-HHmmss
    protected abstract @NonNull String getBaseState();
}
