package com.lanyuanxiaoyao.service.configuration.utils;

import cn.hutool.core.util.StrUtil;
import java.util.Comparator;
import java.util.function.Function;
import org.eclipse.collections.api.map.ImmutableMap;

/**
 * 生成字段比较器
 *
 * @author lanyuanxiaoyao
 * @date 2023-04-21
 */
public class ComparatorUtil {
    public static final String ASC = "asc";
    public static final String DESC = "desc";

    public static <T> Comparator<T> longComparator(String order, String direction, ImmutableMap<String, Function<T, Long>> getters) {
        if (StrUtil.isBlank(order) || StrUtil.isBlank(direction) || !getters.containsKey(order)) {
            return (o1, o2) -> 0;
        }
        Function<T, Long> getter = getters.get(order);
        if (DESC.equalsIgnoreCase(direction)) {
            return (o1, o2) -> Long.compare(getter.apply(o2), getter.apply(o1));
        } else if (ASC.equalsIgnoreCase(direction)) {
            return Comparator.comparingLong(getter::apply);
        } else {
            return (o1, o2) -> 0;
        }
    }

    public static <T> Comparator<T> stringComparator(String order, String direction, ImmutableMap<String, Function<T, String>> getters) {
        if (StrUtil.isBlank(order) || StrUtil.isBlank(direction) || !getters.containsKey(order)) {
            return (o1, o2) -> 0;
        }
        Function<T, String> getter = getters.get(order);
        if (DESC.equalsIgnoreCase(direction)) {
            return (o1, o2) -> StrUtil.compare(getter.apply(o2), getter.apply(o1), true);
        } else if (ASC.equalsIgnoreCase(direction)) {
            return (o1, o2) -> StrUtil.compare(getter.apply(o1), getter.apply(o2), true);
        } else {
            return (o1, o2) -> 0;
        }
    }
}
