package com.yeejoin.amos.boot.module.jg.biz.edit.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiPredicate;

import static com.yeejoin.amos.boot.module.jg.biz.edit.utils.JsonDiffUtil.isNullOrEmpty;

public class DiffUtils {
    private static final Map<String, BiPredicate<String, String>> comparatorFactory = new ConcurrentHashMap<>();

    static {
        registerDefaultComparators();
    }

    private static void registerDefaultComparators() {
        comparatorFactory.put(String.class.getSimpleName(), StringUtils::equals);
        comparatorFactory.put(JSON.class.getSimpleName(), JsonDiffUtil::jsonEqualsIgnoreType);
    }

    public static void register(String type, BiPredicate<String, String> comparator) {
        comparatorFactory.put(type, comparator);
    }

    public static boolean compare(String type, String newValue, String oldValue) {
        if (isNullOrEmpty(newValue) && isNullOrEmpty(oldValue)) return true;
        if (isNullOrEmpty(newValue) || isNullOrEmpty(oldValue)) return false;
        if (type == null) {
            return Objects.equals(newValue, oldValue);
        }
        return comparatorFactory.getOrDefault(type, Objects::equals).test(newValue, oldValue);
    }
}

