package com.usoftchina.bi.core.utils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

/**
 * @author yingp
 * @date 2018/9/30
 */
public class JsonUtils {

    private static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper()
                .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .setTimeZone(TimeZone.getTimeZone("GMT+8"));
    }

    public static String toJsonString(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T fromJsonString(String json, Class<T> targetCls) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return mapper.readValue(json, targetCls);
        } catch (Exception e) {
            return null;
        }
    }

    public static JavaType getJavaType(Class<?> targetClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(targetClass, elementClasses);
    }

    public static JavaType getJavaType(Class<?> targetClass, JavaType... parameterTypes) {
        return mapper.getTypeFactory().constructParametricType(targetClass, parameterTypes);
    }

    public static <T> T fromJsonString(String json, Class<?> targetClass, Class<?>... elementClasses) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return mapper.readValue(json, getJavaType(targetClass, elementClasses));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T fromJsonString(String json, JavaType type) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return mapper.readValue(json, type);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> List<T> fromJsonArray(String json, Class<T> targetCls) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            if (!json.startsWith("[")) {
                json = "[" + json + "]";
            }
            return mapper.readValue(json, getJavaType(List.class, targetCls));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
