package cn.exploring.engine.server.db.util;

import cn.zhxu.bs.operator.Contain;
import cn.zhxu.bs.util.FieldFns;
import cn.zhxu.bs.util.MapBuilder;
import cn.zhxu.bs.util.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class SqlUtil {

    public static String likeStr(String str) {
        return Optional.ofNullable(str)
                .filter(StringUtils::isNotBlank)
                .map(String::trim)
                .map(s -> StrUtil.format("%{}%", s.replaceAll("\\s+", "%")))
                .orElse("%");
    }

    public static List<String> likeList(String str) {
        return Optional.ofNullable(str)
                .filter(StringUtils::isNotBlank)
                .map(String::trim)
                .map(s -> s.replaceAll("\\s+", " "))
                .map(s -> s.split(" "))
                .map(Arrays::asList)
                .orElse(Collections.emptyList());
    }

    public static<T> MapBuilder like (MapBuilder wrapperBuilder, FieldFns.FieldFn<T, ?> fieldFn, String str) {
        likeList(str).forEach(s -> {
            wrapperBuilder.field(fieldFn, s).op(Contain.class);
        });

        return wrapperBuilder;
    }

    public static MapBuilder page(MapBuilder wrapperBuilder, Integer page, Integer size, String column, String order) {
        if (Objects.nonNull(page) && Objects.nonNull(size)) {
            wrapperBuilder.page(page - 1, size);
        }

        if (StringUtils.isNotBlank(column)) {
            wrapperBuilder.orderBy(column,
                    Optional.ofNullable(order)
                            .filter(StringUtils::isNotBlank)
                            .filter(o -> StringUtils.equalsIgnoreCase("desc", o))
                            .map(o ->"desc").orElse("asc")
            );
        }

        return wrapperBuilder;
    }
}
