package me.chyxion.tigon.webmvc.exception;

import java.util.Map;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import me.chyxion.tigon.exception.BaseException;
import me.chyxion.tigon.webmvc.JSONViewDataModel;
import me.chyxion.tigon.exception.InvalidParamException;
import me.chyxion.tigon.exception.InvalidStateException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.MissingServletRequestParameterException;

/**
 * @version 0.0.1
 * @since 0.0.3
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Feb 3, 2015 2:06:58 PM
 */
@Slf4j
@Order(64)
public class DefaultExceptionResolver implements ExceptionResolver {
    @Autowired(required = false)
    private ExceptionMessage exceptionMessage;

    private static final Map<Class<? extends Throwable>, Integer> EXCEPTIONS_MAP = 
            new HashMap<Class<? extends Throwable>, Integer>() {
        private static final long serialVersionUID = 1L;
        {
            // Database Exceptions
            // 4002
            put(IllegalStateException.class, InvalidStateException.CODE);
            put(ConversionFailedException.class, InvalidStateException.CODE);
            put(IllegalArgumentException.class, InvalidStateException.CODE);
            // 4001
            put(InvalidParamException.class, InvalidParamException.CODE);
            put(MissingServletRequestParameterException.class, InvalidParamException.CODE);
            put(ServletRequestBindingException.class, InvalidParamException.CODE);
        }
    };

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean accept(Throwable ex) {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public JSONViewDataModel process(JSONViewDataModel model) {
        Throwable ex = model.getException();
        log.error("Exception [{}] [{}] Caused.", ex.getClass(), ex.getMessage(), ex);
        Object code = model.getCode();
        if (code == null || 
            (code instanceof Number && ((Number) code).intValue() == 0) ||
            (code instanceof String && StringUtils.isBlank((String) code))) {
            code = getErrorCode(ex);
            if (code == null) {
                code = BaseException.CODE;
            }
            model.setCode(code);
        }
        if (model.getMessage() == null) {
            Object message = null;
            if (exceptionMessage != null) {
                message = exceptionMessage.get(code);
                log.info("Get Custom Error Message [{}] By Code [{}].", message, code);
            }
            if (message == null) {
                message = getErrorMessage(ex, code);
            }
            model.setMessage(message);
        }
        return model;
    }

    /**
     * @param ex exception
     * @return error code
     */
    protected Object getErrorCode(Throwable ex) {
        return EXCEPTIONS_MAP.get(ex.getClass());
    }

    /**
     * @param ex exception
     * @param code error code
     * @return error message
     */
    protected Object getErrorMessage(Throwable ex, Object code) {
        Object message = null;
        for (Throwable e : ExceptionUtils.getThrowableList(ex)) {
            String msg = e.getMessage();
            if (StringUtils.isNotBlank(msg)) {
                message = msg;
                break;
            }
        }
        log.info("No Custom Error Message Found, Get Message [{}] From Exception.", message);
        return message;
    }
}
