package com.njzscloud.common.core.ex;

import cn.hutool.core.util.StrUtil;

/**
 * 异常工具类
 * 创建异常对象
 */
public class Exceptions {

    public static SysThrowable clierr(Object message, Object... param) {
        return build(null, ExpectData.NULL_DATA, ExceptionMsg.CLI_ERR_MSG, message, param);
    }

    public static SysThrowable clierr(Object message) {
        return build(null, ExpectData.NULL_DATA, ExceptionMsg.CLI_ERR_MSG, message, null);
    }

    public static SysThrowable exception(Object message, Object... param) {
        return build(null, ExpectData.NULL_DATA, ExceptionMsg.SYS_EXP_MSG, message, param);
    }

    public static SysThrowable exception(Object message) {
        return build(null, ExpectData.NULL_DATA, ExceptionMsg.SYS_EXP_MSG, message, null);
    }

    public static SysThrowable error(Object message, Object... param) {
        return build(null, ExpectData.NULL_DATA, ExceptionMsg.SYS_ERR_MSG, message, param);
    }

    public static SysThrowable error(Object message) {
        return build(null, ExpectData.NULL_DATA, ExceptionMsg.SYS_ERR_MSG, message, null);
    }

    public static SysThrowable error(Throwable cause, Object message, Object... param) {
        return build(cause, ExpectData.NULL_DATA, ExceptionMsg.SYS_ERR_MSG, message, param);
    }

    public static SysThrowable error(Throwable cause, Object message) {
        return build(cause, ExpectData.NULL_DATA, ExceptionMsg.SYS_ERR_MSG, message, null);
    }

    /**
     * <p>创建异常对象</p>
     *
     * @param cause   嵌套异常
     * @param expect  期望值
     * @param msg     异常信息
     * @param message 详细信息(字符串模板, 占位符: {})
     * @param param   模板参数
     * @see SysThrowable
     * @see ExceptionMsg
     * @see ExpectData
     */
    private static SysThrowable build(Throwable cause, ExpectData expect, ExceptionMsg msg, Object message, Object[] param) {

        if (message instanceof String
                && !StrUtil.isBlank((String) message)
                && param != null
                && param.length > 0) {
            message = StrUtil.format((String) message, param);
        }

        SysThrowable sysThrowable;

        if (msg.type == ExceptionType.SYS_EXP) {
            sysThrowable = new SysException(cause, expect, msg, message);
        } else if (msg.type == ExceptionType.CLI_ERR) {
            sysThrowable = new CliException(cause, expect, msg, message);
        } else {
            sysThrowable = new SysError(cause, expect, msg, message);
        }

        return sysThrowable;
    }

}
