package com.wishurgift.utils;

import com.wishurgift.service.dto.ErrorDTO;
import com.wishurgift.wrapper.Result;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class ResponseUtils {

    public static Response make(Result result) {
        Response.ResponseBuilder response;
        if (result.isSuccess()) {
            response = Response.status(Response.Status.OK);
        } else {
            ErrorDTO error = (ErrorDTO) result.getData();
            response = Response.status(errorCodeToHttpStatusMapper(error.getCode()));
        }
        return response.entity(result)
                .type(MediaType.APPLICATION_JSON)
                .build();
    }

    private static Response.Status errorCodeToHttpStatusMapper(int code) {
        Response.Status status = Response.Status.fromStatusCode(code);
        if (status == null) {
            status = Response.Status.BAD_REQUEST;
        }
        return status;
    }

}
