package ru.yandex.webmaster3.core.codes;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * User: azakharov
 * Date: 27.01.15
 * Time: 13:46
 */

public enum DownloadedHttpCodeGroup implements ICodeGroup {
    DOWNLOADED_2XX(HttpCodeGroup.HTTP_GROUP_2XX, HttpCodeGroup.HTTP_GROUP_2XXX),
    DOWNLOADED_3XX(HttpCodeGroup.HTTP_GROUP_3XX),
    DOWNLOADED_4XX(HttpCodeGroup.HTTP_GROUP_4XX),
    DOWNLOADED_5XX(HttpCodeGroup.HTTP_GROUP_5XX),
    DOWNLOADED_COULD_NOT_DOWNLOAD();//HttpCodeGroup.HTTP_GROUP_1XXX, HttpCodeGroup.HTTP_GROUP_3XXX),
    //DOWNLOADED_INCORRECT_RESPONSE();

    private final Set<HttpCodeGroup> httpCodeGroups = new HashSet<>();

    DownloadedHttpCodeGroup(HttpCodeGroup... httpCodeGroups) {
        this.httpCodeGroups.addAll(Arrays.asList(httpCodeGroups));
    }

    public static Optional<DownloadedHttpCodeGroup> get(Integer httpCode) {
        if (httpCode == null) {
            return Optional.empty();
        }

        for (DownloadedHttpCodeGroup g : DownloadedHttpCodeGroup.values()) {
            if (g.httpCodeGroups.stream().anyMatch(c -> c.contains(httpCode))) {
                return Optional.of(g);
            }
        }

        return Optional.of(DOWNLOADED_COULD_NOT_DOWNLOAD);
    }

    public boolean contains(HttpCodeGroup httpCodeGroup) {
        for (HttpCodeGroup g : httpCodeGroups) {
            if (g.contains(httpCodeGroup)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean contains(Integer httpCode) {
        for (HttpCodeGroup g : httpCodeGroups) {
            if (g.contains(httpCode)) {
                return true;
            }
        }

        return false;
    }
}
