package com.lanyuanxiaoyao.service.command.utils;

import cn.hutool.core.util.StrUtil;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * 过滤使用
 *
 * @author ZhangJiacheng
 * @date 2022-04-29
 */
public class SearchUtils {
    public enum Type {
        /**
         * 什么都不操作
         */
        NONE,
        /**
         * 正则表达式
         */
        REGEX,
        /**
         * 包含
         */
        CONTAINS,
        /**
         * 不包含
         */
        UN_CONTAINS,
        /**
         * 等于
         */
        EQUALS,
        /**
         * 不等于
         */
        UN_EQUALS
    }

    public static Boolean search(Type type, String patternInput, String value) {
        String pattern = patternInput.trim();
        Stream<String> patterns = Arrays.stream(pattern.split(","));
        switch (type) {
            case REGEX:
                if (StrUtil.isBlank(pattern)) {
                    throw new RuntimeException("Regex pattern cannot be blank");
                }
                return value.matches(pattern);
            case CONTAINS:
                return patterns.anyMatch(value::contains);
            case UN_CONTAINS:
                return patterns.noneMatch(value::contains);
            case EQUALS:
                return patterns.anyMatch(value::equals);
            case UN_EQUALS:
                return patterns.noneMatch(value::equals);
            case NONE:
                return true;
            default:
                throw new RuntimeException("Unsupported search type");
        }
    }
}
