package ru.yandex.webmaster3.viewer.http.importanturls;

import ru.yandex.webmaster3.core.codes.HttpCodeGroup;
import ru.yandex.webmaster3.storage.importanturls.data.ImportantUrl;
import ru.yandex.webmaster3.storage.importanturls.data.ImportantUrlStatus;

import java.util.EnumMap;
import java.util.Optional;

/**
 * Created by Oleg Bazdyrev on 05/03/2019.
 */
final class ImportantUrlsStatCollector {
    private final EnumMap<ImportantUrlsStatGroup, Integer> map = new EnumMap<>(ImportantUrlsStatGroup.class);

    public void update(ImportantUrl url) {
        increment(ImportantUrlsStatGroup.TOTAL_URLS);
        Optional<ImportantUrlStatus.IndexingInfo> indexingInfo = Optional.of(url)
                .map(ImportantUrl::getLastStatus)
                .map(ImportantUrlStatus::getIndexingInfo);
        if (!indexingInfo.isPresent()) {
            increment(ImportantUrlsStatGroup.URLS_NOT_INDEXED_YET);
            return;
        }
        HttpCodeGroup code = indexingInfo.get().getHttpCode().getHttpCodeGroup();
        if (HttpCodeGroup.HTTP_GROUP_1XX_ALL.contains(code)) {
            increment(ImportantUrlsStatGroup.URLS_WITH_CODE_1XX);
        } else if (HttpCodeGroup.HTTP_GROUP_2XX.contains(code)) {
            increment(ImportantUrlsStatGroup.URLS_WITH_CODE_2XX);
        } else if (HttpCodeGroup.HTTP_GROUP_3XX.contains(code)) {
            increment(ImportantUrlsStatGroup.URLS_WITH_CODE_3XX);
        } else if (HttpCodeGroup.HTTP_GROUP_4XX.contains(code)) {
            increment(ImportantUrlsStatGroup.URLS_WITH_CODE_4XX);
        } else if (HttpCodeGroup.HTTP_GROUP_5XX.contains(code)) {
            increment(ImportantUrlsStatGroup.URLS_WITH_CODE_5XX);
        } else {
            // в этом случае код расширенный
            increment(ImportantUrlsStatGroup.URLS_NA);
        }
    }

    public EnumMap<ImportantUrlsStatGroup, Integer> getResult() {
        return map;
    }

    private void increment(ImportantUrlsStatGroup key) {
        map.put(key, map.getOrDefault(key, 0) + 1);
    }

}
