package cz.senslog.analytics.server.ws;

import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.validation.ParameterProcessorException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Optional;

import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE;


public final class ExceptionHandler implements io.vertx.core.Handler<RoutingContext> {

    private static final Logger logger = LogManager.getLogger(ExceptionHandler.class);

    private static final String DEFAULT_ERROR_MESSAGE = "Something went wrong!";

    public static ExceptionHandler createAsJSON() {
        return new ExceptionHandler();
    }

    private static int codeByException(Throwable throwable, int defaultCode) {
        if (throwable instanceof ParameterProcessorException) {
            return  400;
        } else if (throwable instanceof HttpIllegalArgumentException) {
            return ((HttpIllegalArgumentException)throwable).getCode();
        }
        return defaultCode;
    }

    @Override
    public void handle(RoutingContext rc) {
        Throwable th = Optional.ofNullable(rc.failure()).orElse(new Throwable(DEFAULT_ERROR_MESSAGE));

        String message = th.getMessage();
        int code = codeByException(th, rc.statusCode());

        logger.error(message);
        rc.response()
                .putHeader(CONTENT_TYPE, ContentType.JSON.contentType())
                .setStatusCode(code)
                .end(JsonObject.of(
                        "code", code,
                        "message", message
                ).encode());
    }
}
