package ru.yandex.webmaster3.storage.jupiter;

import lombok.RequiredArgsConstructor;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.storage.searchbase.dao.SearchBaseUpdatesYDao;
import ru.yandex.webmaster3.storage.util.yt.YtException;
import ru.yandex.webmaster3.storage.util.yt.YtNode;
import ru.yandex.webmaster3.storage.util.yt.YtPath;
import ru.yandex.webmaster3.storage.util.yt.YtService;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("jupiterUtils")
public class JupiterUtils {

    public static final DateTimeFormatter STATE_DATE_FORMAT = DateTimeFormat.forPattern("yyyyMMdd'-'HHmmss")
            .withZone(DateTimeZone.forID("Europe/Moscow"));
    public static final DateTimeFormatter STATE_DATE_FORMAT_FOR_CH_TABLE = DateTimeFormat.forPattern("yyyyMMddHHmmss")
            .withZone(DateTimeZone.forID("Europe/Moscow"));
    private final YtService ytService;
    private final SearchBaseUpdatesYDao searchBaseUpdatesYDao;
    @Value("${webmaster3.storage.jupiter.baseMeta.ytPath}")
    private YtPath jupiterPath;

    public YtPath getPriemkaPathExport() {
        final String priemkaState = getPriemkaState();
        return YtPath.path(jupiterPath, "export/" + priemkaState);
    }

    public YtPath getCurrentPathExport() {
        final String currentState = getCurrentState();
        return YtPath.path(jupiterPath, "export/" + currentState);
    }

    public String getCurrentState() {
        return getCurrentBaseCollectionDate().toString(STATE_DATE_FORMAT);
    }

    public Instant getCurrentBaseCollectionDate() {
        return searchBaseUpdatesYDao.getUpdatesHistory().lastEntry().getValue().getBaseCollectionDate();
    }

    // format from yyyyMMdd-HHmmss to yyyyMMddHHmmss
    public static String getStateWithOnlyDigits(String state) {
        return state.replace("-", "");
    }

    public String getPriemkaState() {
        return getAttributeForJupiterTable("dessert_prev_state");
    }

    public String getPreviouslyState() {
        return getAttributeForJupiterTable("production_prev_state");
    }

    private String getAttributeForJupiterTable(String attributeName) {
        return ytService.inTransaction(jupiterPath).query(cypressService -> {
            final String productionState;
            final YtNode node = cypressService.getNode(jupiterPath);
            if (node != null) {
                productionState = node.getNodeMeta()
                        .get("jupiter_meta")
                        .get(attributeName)
                        .asText();

            } else {
                throw new YtException("Expected table with path " + jupiterPath);
            }
            return productionState;
        });
    }

    public static Instant getBaseDateFromPath(String path) {
        for (String part : path.split("/")) {
            try {
                return STATE_DATE_FORMAT.parseDateTime(part).toInstant();
            } catch (IllegalArgumentException ignored) {
            }
        }
        return null;
    }

}
