package ru.yandex.webmaster3.core.data;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.codes.HttpCodeGroup;
import ru.yandex.wmtools.common.util.http.YandexHttpStatus;

/**
 * User: azakharov
 * Date: 16.03.15
 * Time: 16:50
 */
public class HttpCodeInfo {
    private final Integer code;
    private final YandexHttpStatus status;
    private final HttpCodeGroup httpCodeGroup;

    public HttpCodeInfo(Integer httpCode, YandexHttpStatus httpStatus) {
        this(httpCode, httpStatus, false);
    }

    public HttpCodeInfo(Integer httpCode) {
        this(httpCode, false);
    }

    public HttpCodeInfo(Integer httpCode, YandexHttpStatus httpStatus, boolean downloaded) {
        this.httpCodeGroup = downloaded ? HttpCodeGroup.getForDownloaded(httpCode) : HttpCodeGroup.get(httpCode);
        this.code = httpCode;
        this.status = httpStatus;
    }

    public HttpCodeInfo(Integer httpCode, boolean downloaded) {
        this.httpCodeGroup = downloaded ? HttpCodeGroup.getForDownloaded(httpCode) : HttpCodeGroup.get(httpCode);
        this.code = httpCode;

        if (code == null) {
            this.status = YandexHttpStatus.UNKNOWN;
        } else {
            this.status = YandexHttpStatus.parseCode(httpCode);
        }
    }

    @JsonCreator
    public HttpCodeInfo(
            @JsonProperty("code") Integer code,
            @JsonProperty("status") YandexHttpStatus status,
            @JsonProperty("httpCodeGroup") HttpCodeGroup httpCodeGroup) {
        this.code = code;
        this.status = status;
        this.httpCodeGroup = httpCodeGroup;
    }

    @Description("Реальный http-код")
    public Integer getCode() {
        return code;
    }

    @Description("Группа кодов")
    public HttpCodeGroup getHttpCodeGroup() {
        return httpCodeGroup;
    }

    @Description("Статус из известных")
    public YandexHttpStatus getStatus() {
        return status;
    }

    @Override
    public String toString() {
        return "HTTP " + code + " (" + status + ")";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        HttpCodeInfo that = (HttpCodeInfo) o;

        if (!code.equals(that.code)) {
            return false;
        }
        return status == that.status;

    }

    @Override
    public int hashCode() {
        int result = code.hashCode();
        result = 31 * result + status.hashCode();
        return result;
    }

    public static HttpCodeInfo fromHttpStatus(YandexHttpStatus httpStatus) {
        return new HttpCodeInfo(httpStatus.getCode(), httpStatus);
    }
}
