package me.chyxion.tigon.webmvc;

import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import me.chyxion.tigon.webmvc.exception.ExceptionResolver;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @since 0.0.1
 * @author Donghuang <br>
 * donghuang@wacai.com <br>
 * Jul 18, 2014 8:50:17 AM
 */
@Slf4j
@Order
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class TigonControllerAdvice {

    @Autowired
    private JSONViewConfig jsonViewConfig;
    @Autowired
    private List<ExceptionResolver> exceptionResolvers;

    @ExceptionHandler(Throwable.class)
    public ModelAndView handleThrowable(Throwable ex) {
        log.warn("Exception [{}] [{}] Caused.", ex.getClass(), ex.getMessage());
        JSONViewDataModel model = new JSONViewDataModel(ex).setSuccess(false);
        // custom exception resolvers
        for (ExceptionResolver er : exceptionResolvers) {
            if (log.isInfoEnabled()) {
                log.info("Exception Resolver [{}] Found.", er.getClass());
            }
            if (er.accept(ex)) {
                log.info("Exception Has Been Accepted By [{}].", er);
                model = er.process(model);
                break;
            }
        }
        return new ModelAndView(new JSONView(model, jsonViewConfig));
    }
}
