package com.tzld.piaoquan.ad.engine.commons.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.reflect.TypeToken;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

public class JSONUtils {

    private static final Logger log = LoggerFactory.getLogger(JSONUtils.class);

    public static String toJson(Object obj, Collection<String> ignoreFieldName) {
        if (Objects.isNull(obj)) {
            return "";
        }
        try {

            ExclusionStrategy strategy = new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                    return CollectionUtils.isNotEmpty(ignoreFieldName) &&
                            ignoreFieldName.contains(fieldAttributes.getName());
                }

                @Override
                public boolean shouldSkipClass(Class<?> aClass) {
                    return false;
                }
            };
            return new GsonBuilder().setExclusionStrategies(strategy).create().toJson(obj);
        } catch (Exception e) {
            log.error("toJsonIgnoreField exception: ", e);
            return "";
        }
    }

    public static String toJson(Object obj) {
        if (obj == null) {
            return "";
        }
        try {
            return new Gson().toJson(obj);
        } catch (Exception e) {
            log.error("toJson exception", e);
            return "";
        }
    }

    public static <T> T fromJson(String value, TypeToken<T> typeToken, T defaultValue) {

        if (StringUtils.isBlank(value)) {
            return defaultValue;
        }
        try {
            return JSONObject.parseObject(value, typeToken.getType());
        } catch (Exception e) {
            log.error("parseObject error! value=[{}]", value, e);
        }
        return defaultValue;
    }

}
