package ru.yandex.qe.bus.exception;

import java.lang.reflect.Constructor;

import javax.annotation.Nonnull;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import org.apache.cxf.jaxrs.client.ResponseExceptionMapper;
import org.apache.cxf.jaxrs.utils.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResponseToExceptionMapper
        implements ResponseExceptionMapper<Throwable> {

    private static final Logger log = LoggerFactory.getLogger(ResponseToExceptionMapper.class);

    @Override
    public Throwable fromResponse(@Nonnull final Response response) {
        return createDefaultWae(response);
    }

    private static Throwable createDefaultWae(Response r) {
        try {
            Class<?> exceptionClass = ExceptionUtils.getWebApplicationExceptionClass(r, WebApplicationException.class);
            Constructor<?> ctr = exceptionClass.getConstructor(String.class, Response.class);
            return (WebApplicationException) ctr.newInstance(readContent(r), r);
        } catch (Throwable e) {
            log.warn("Cannot construct exception", e);
            return new WebApplicationException(r);
        }
    }

    private static String readContent(Response r) {
        return r.hasEntity() ? r.readEntity(String.class) : null;
    }
}
