package com.mosty.common.base.exception;


import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

/**
 * 断言，快速业务异常
 * @author kevin
 * @date 2022/4/28 1:49 下午
 * @since 1.0.0
 */
@SuppressWarnings("unused")
public class Asserts {

    private Asserts() {
    }


    public static void directThrow(RuntimeException exception) {
        throw exception;
    }

    /**
     *  断言 抛出 {@link BusinessExceptionEnum} 对应的业务异常
     * @param expression 表达式
     * @param message 异常信息
     */
    public static void checkAuth(boolean expression, String message) {
        if (expression) {
            throw new BusinessException(HttpStatus.UNAUTHORIZED.value(), message);
        }
    }

    /**
     *  断言 抛出 {@link BusinessExceptionEnum} 对应的业务异常
     * @param expression 表达式
     * @param message 异常信息
     * @param args 参数信息
     */
    public static void checkAuth(boolean expression, String message, Object... args) {
        if (expression) {
            throw new BusinessException(HttpStatus.UNAUTHORIZED.value(), String.format(message, args));
        }
    }

    public static void check(boolean expression, String message) {
        if (expression) {
            throw new BusinessException(message);
        }
    }

    /**
     * 断言 抛出 {@link BusinessExceptionEnum} 对应的业务异常
     * @param expression 表达式
     * @param exceptionEnum 业务异常
     */
    public static void check(boolean expression, BusinessExceptionEnum exceptionEnum) {
        check(expression, exceptionEnum.message);
    }

    public static void check(boolean expression, RuntimeException e) {
        if (expression) {
            throw e;
        }
    }

    public static void check(boolean expression, String message, Object... args) {
        if (expression) {
            throw new BusinessException(String.format(message, args));
        }
    }

    public static void check(boolean expression, String message, Object arg) {
        if (expression) {
            throw new BusinessException(String.format(message, arg));
        }
    }

    public static void notNull(Object object, String name) {
        if (object == null) {
            throw new BusinessException(name + " is null");
        }
    }

    public static void notEmpty(CharSequence s, String name) {
        if (StringUtils.isEmpty(s)) {
            throw new BusinessException(name + " is empty");
        }
    }

    public static void notBlank(CharSequence s, String name) {
        if (StringUtils.isBlank(s)) {
            throw new BusinessException(name + " is blank");
        }
    }
}