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

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.internal.scm.git.lfs.BadBatchRequestException;
import com.atlassian.bitbucket.internal.scm.git.lfs.model.RequestObject;
import org.codehaus.jackson.map.annotate.JsonSerialize;

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

/**
 * An object descriptor for the Batch API Request
 */
@JsonSerialize
public class RestRequestObject extends RestBaseObject {

    public RestRequestObject(@Nonnull RequestObject requestObject) {
        super(requestObject);
    }

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

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

    @Nonnull
    public RequestObject fromRest(@Nonnull I18nService i18nService) {
        return new RequestObject(getOid(i18nService), getSize(i18nService));
    }

    @Nonnull
    private String getOid(@Nonnull I18nService i18nService) {
        String oid = getStringProperty(OID_KEY);
        if (oid == null) {
            throw new BadBatchRequestException(i18nService.getMessage(
                    "bitbucket.scm.git.lfs.request.missing.attribute", "oid"));
        }
        return oid;
    }

    private long getSize(I18nService i18nService) {
        if (!containsKey(SIZE_KEY)) {
            throw new BadBatchRequestException(i18nService.getMessage(
                    "bitbucket.scm.git.lfs.request.missing.attribute", "size"));
        }

        try {
            return getLongProperty(SIZE_KEY);
        } catch (NumberFormatException e) {
            throw new BadBatchRequestException(i18nService.getMessage("bitbucket.scm.git.lfs.request.invalid.size"));
        }
    }
}
