package ru.yandex.webmaster3.core.turbo.model.error;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.wmtools.common.util.http.YandexHttpStatus;

import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * Информация об ошибке
 */
public final class TurboError {

    public static final TypeReference<List<TurboError>> TYPE_REFERENCE =
            new TypeReference<List<TurboError>>() {
            };

    public static final Predicate<ObjectNode> IS_DISALLOWED_IN_ROBOTS = details -> {
        if (details != null) {
            JsonNode httpCode = details.get("http_code");
            return httpCode != null && httpCode.asInt() == YandexHttpStatus.HTTP_1003_ROBOTS_TXT_DISALLOW.getCode();
        }
        return false;
    };
    private final TurboErrorType type;
    private final int count;
    private final List<TurboErrorSample> samples;

    @JsonCreator
    public TurboError(TurboErrorType type, int count, List<TurboErrorSample> samples) {
        this.type = type;
        this.count = count;
        this.samples = samples;
    }

    @Description("Тип ошибки")
    @JsonProperty("code")
    public TurboErrorType getType() {
        return type;
    }

    @Description("Количество ошибок данного типа")
    public int getCount() {
        return count;
    }

    @Description("Примеры ошибок")
    @JsonProperty("items")
    public List<TurboErrorSample> getSamples() {
        return samples;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TurboError that = (TurboError) o;
        return count == that.count &&
                type == that.type &&
                Objects.equals(samples, that.samples);
    }

    @Override
    public int hashCode() {
        return Objects.hash(type, count);
    }
}
