package eu.eudat.controllers.controllerhandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import eu.eudat.core.models.exception.ApiExceptionLoggingModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import types.LoggingType;

import javax.annotation.Priority;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ikalyvas on 6/12/2018.
 */
@ControllerAdvice
@Priority(5)
public class ControllerErrorHandler {
    private static final Logger logger = LoggerFactory.getLogger(ControllerErrorHandler.class);

//    private Logger logger;

    /*@Autowired
    public ControllerErrorHandler(Logger logger) {
        this.logger = logger;
    }*/

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseItem<Exception> processValidationError(Principal principal, Exception ex) throws Exception {
        ApiExceptionLoggingModel<String, Principal> apiExceptionLoggingModel = new ApiExceptionLoggingModel<>();
        apiExceptionLoggingModel.setCode(HttpStatus.BAD_REQUEST);
        apiExceptionLoggingModel.setUser(principal);
        Map<String, String> exceptionMap = new HashMap<>();
        ObjectWriter ow = new ObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false).writer().withDefaultPrettyPrinter();
        try {
            String json = ow.writeValueAsString(ex);
            exceptionMap.put("exception", json);
            apiExceptionLoggingModel.setData(ow.writeValueAsString(exceptionMap));
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
        }
        apiExceptionLoggingModel.setMessage(ex.getMessage());
        apiExceptionLoggingModel.setType(LoggingType.ERROR);
        logger.error(ex.getMessage(), ex);
        return new ResponseItem<Exception>().message(ex.getMessage()).status(ApiMessageCode.DEFAULT_ERROR_MESSAGE);
    }
}
