package cn.edu.whu.boot.common.domain;

import cn.edu.whu.boot.allocation.exceptions.InvalidShapefileException;
import cn.edu.whu.boot.allocation.exceptions.InvalidAssignmentStatus;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.sql.SQLException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 全局异常处理类
 *
 * @author CXJ
 */
@ControllerAdvice
public class GlobalExceptionHandler{

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handle(HttpServletRequest req, Exception exception){
        log.error(ExceptionUtils.getStackTrace(exception));

        ExceptionInfo<String> exceptionInfo = new ExceptionInfo<>();
        String info;
        if(exception instanceof NullPointerException){
            info = "空指针错误";
        }
        else if(exception instanceof InvalidPathException){
            info = "文件路径错误";
        }
        else if(exception instanceof IOException){
            info = "读写文件时发生异常";
        }
        else if(exception instanceof UnauthenticatedException){
            info = "用户未认证";
        }
        else if(exception instanceof UnauthorizedException){
            info = "用户权限不足";
        }
        else if(exception instanceof AuthenticationException){
            info = "用户认证失败";
        }
        else if(exception instanceof DuplicateKeyException){
            info = exception.getMessage();
            if(info.contains("unique_username")){
                info = "用户名已被使用";
            }
            else if(info.contains("unique_phone")){
                info = "手机号码已被使用";
            }
            else if(info.contains("unique_email")){
                info = "邮箱已被使用";
            }
        }
        else if(exception instanceof ConstraintViolationException){
            info = Stream.of(exception.getMessage().split(",")).map(message -> message.substring(message.indexOf(": ") + ": ".length())).collect(Collectors.joining("，"));
        }
        else if(exception instanceof SQLException){
            info = "操作数据库时发生异常";
        } else if (exception instanceof InvalidAssignmentStatus) {
            info = exception.getMessage();
        } else if (exception instanceof InvalidShapefileException) {
            info = exception.getMessage();
        } else {
            info = "程序内部错误";
        }
        exceptionInfo.setCode(ExceptionInfo.ERROR);
        exceptionInfo.setMessage(info);
        exceptionInfo.setData(null);
        exceptionInfo.setUrl(req.getRequestURL().toString());
        return exceptionInfo.toString();
    }
}