package com.bcxin.Infrastructures.components;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bcxin.Infrastructures.exceptions.BadTenantException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collection;

public interface JsonProvider {
    <T> String getJson(T data);

    <T> T toObject(Class<T> tClass, String json);

    <T> Collection<T> toObjects(Class<T> tClass, String json);

    @Component
    static class DefaultJsonProvider implements JsonProvider {
        @Override
        public <T> String getJson(T data) {
            if(data==null) {
                return null;
            }

            return JSON.toJSONString(data, SerializerFeature.WriteMapNullValue);
        }

        @Override
        public <T> T toObject(Class<T> tClass, String json) {
            try {
                if (!StringUtils.hasLength(json)) {
                    return null;
                }
                return JSON.parseObject(json, tClass);
            } catch (Exception ex) {
                //todo: 数据异常
                throw new BadTenantException(String.format("数据异常:%s 预期类:%s", json, tClass));
            }
        }

        @Override
        public <T> Collection<T> toObjects(Class<T> tClass, String json) {
            return JSON.parseArray(json, tClass);
        }
    }
}
