package com.sonic.common.exception;

import com.sonic.common.rpc.ApiResultCode;
import com.sonic.common.rpc.GlobalResultCode;
import lombok.experimental.UtilityClass;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author: chen
 * @date: 2020/05/14
 * @Description:
 * @version: 1.0.0
 */
@UtilityClass
public class BizExceptionUtils {

    public static void check(boolean expect, String msg) {
        if (expect) {
            throw new BizException(GlobalResultCode.INVALID_PARAMS.getErrorCode(), msg);
        }
    }

	public static void check(boolean expect, String code, String msg) {
		if (expect) {
			throw new BizException(code, msg);
		}
	}

	public static void check(boolean expect, ApiResultCode resultCode) {
		if (expect) {
			throw new BizException(resultCode);
		}
	}

    public static <T extends RuntimeException> void check(boolean expect, Supplier<? extends T> supplier) throws T {
        if (expect) {
            throw supplier.get();
        }
    }

    public static void checkEquals(Object source, Object target, String msg) {
        if (!Objects.equals(source, target)) {
            throw new BizException(GlobalResultCode.SYSTEM_EXCEPTION.getErrorCode(), msg);
        }
    }

    public static void checkNonNull(Object target, String msg) {
        if (Objects.isNull(target)) {
            throw new BizException(GlobalResultCode.SYSTEM_EXCEPTION.getErrorCode(), msg);
        }
    }

    public static void checkNotEmpty(Collection coll, String msg) {
        if (coll == null || coll.isEmpty()) {
            throw new BizException(GlobalResultCode.SYSTEM_EXCEPTION.getErrorCode(), msg);
        }
    }
}
