/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.ui.ws.rs.exceptions;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import com.scytl.products.ov.commons.beans.exceptions.SemanticErrorException;
import com.scytl.products.ov.commons.beans.exceptions.SyntaxErrorException;
import com.scytl.products.ov.commons.beans.exceptions.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.products.ov.commons.ui.ws.rs.ErrorCodes;
import com.scytl.products.ov.commons.ui.ws.rs.HTTPStatus;
import com.scytl.products.ov.commons.ui.ws.rs.Message;

/**
 * Handler which will control the constraints defined for validation purposes
 */
@Provider
public class ValidationExceptionHandler implements ExceptionMapper<ValidationException> {

	private static final String ERROR_MESSAGE_INVALID_ENTITY = "The input data is not valid";

	private static final Logger LOG = LoggerFactory.getLogger(ValidationExceptionHandler.class);
	
	@Override
	public Response toResponse(ValidationException e) {
		LOG.error("An error ocurred: ", e);

		String errorCode = ErrorCodes.VALIDATION_EXCEPTION;
		Message message = new Message();
		message.setText(ERROR_MESSAGE_INVALID_ENTITY);
		message.addError("", "", errorCode);
		if (e instanceof SyntaxErrorException) {
			return Response.status(Status.BAD_REQUEST).build();
		} else if (e instanceof SemanticErrorException) {
			return Response.status(HTTPStatus.UNPROCESSABLE_ENTITY.getValue()).entity(message).build();
		}
		return Response.status(Status.BAD_REQUEST).build();
	}
}
