package cn.axzo.msg.center.utils;

import cn.axzo.msg.center.common.utils.ReflectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @author cold_blade
 * @date 2023/10/13
 * @version 1.0
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JSONObjectUtil {
    private static final String EMPTY_JSON_OBJ_STR = "{}";
    private static final String EMPTY_JSON_ARR_STR = "[]";

    /**
     * 解析JSON字符串，若字符串格式不正确，抛异常
     *
     * @param str 待解析的字符串
     * @return JSONObject
     */
    public static JSONObject parseObject(String str) {
        if (StringUtils.isBlank(str)) {
            return new JSONObject();
        }
        return JSON.parseObject(str);
    }

    /**
     * 解析JSON字符串，若字符串格式不正确，抛异常
     *
     * @param str 待解析的字符串
     * @return JSONObject
     */
    public static <T> T parseObject(String str, Class<T> type) {
        if (StringUtils.isBlank(str)) {
            return ReflectionUtils.newInstance(type);
        }
        return JSON.parseObject(str, type);
    }

    /**
     * 解析JSON字符串，若字符串格式不正确，抛异常
     *
     * @param str 待解析的字符串
     * @return List<T>
     */
    public static <T> List<T> parseArray(String str, Class<T> clazz) {
        if (StringUtils.isBlank(str)) {
            return Collections.emptyList();
        }
        return JSON.parseArray(str, clazz);
    }

    public static String toJSONString(Object obj) {
        if (Objects.isNull(obj)) {
            return EMPTY_JSON_OBJ_STR;
        }
        return JSON.toJSONString(obj);
    }

    public static String toJSONString(Collection<?> objCollection) {
        if (CollectionUtils.isEmpty(objCollection)) {
            return EMPTY_JSON_ARR_STR;
        }
        return JSON.toJSONString(objCollection);
    }

    /**
     * 校验字符串是否为有效的JSON字符串，若字符串格式不正确，抛异常
     *
     * @param str 待校验的字符串
     * @return 原字符串OR空的JSONObject
     */
    public static String checkAndReturn(String str) {
        return parseObject(str).toJSONString();
    }
}
