package com.atlassian.bitbucket.internal.scm.git.lfs.rest.model;

import com.atlassian.bitbucket.internal.scm.git.lfs.BadBatchResponseException;
import com.atlassian.bitbucket.rest.RestMapEntity;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import javax.annotation.Nonnull;
import java.util.Map;

import static java.util.Objects.requireNonNull;

/**
 * This class encapsulates an error response. For example:
 * <pre>
 * "error": {
 *     "code": 404,
 *     "message": "Object not found"
 * }
 * </pre>
 */
@JsonSerialize
public class RestResponseError extends RestMapEntity {

    private static final String CODE_KEY = "code";
    private static final String MESSAGE_KEY = "message";

    public RestResponseError(int code, @Nonnull String message) {
        put(MESSAGE_KEY, requireNonNull(message, "message"));
        put(CODE_KEY, code);
    }

    protected RestResponseError(@Nonnull Map<String, Object> values) {
        super(values);
    }

    @Nonnull
    public static RestResponseError valueOf(@Nonnull Map<String, Object> values) {
        return new RestResponseError(values);
    }

    public int getCode() {
        if (!containsKey(CODE_KEY)) {
            throw new BadBatchResponseException("Missing ''code'' attribute");
        }

        try {
            return getIntProperty(CODE_KEY);
        } catch (NumberFormatException e) {
            throw new BadBatchResponseException("Invalid ''code'' attribute");
        }
    }

    @Nonnull
    public String getMessage() {
        String message = getStringProperty(MESSAGE_KEY);
        if (message == null) {
            throw new BadBatchResponseException("Missing ''message'' attribute");
        }
        return message;
    }
}
