package com.liquidnet.commons.lang.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.text.SimpleDateFormat;

public class JsonUtils {
    private final static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.registerModule(new JavaTimeModule());
    }

    private JsonUtils() {
    }

    public static ObjectMapper OM() {
        return objectMapper.copy();
    }

    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("readJson JsonProcessingException", e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        if (null == json || "".equals(json.trim()) || null == clazz) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("readJson JsonProcessingException", e);
        }
    }

    public static <T> T fromJson(String json, TypeReference<T> valueOfType) {
        if (null == json || "".equals(json.trim()) || null == valueOfType) {
            return null;
        }
        try {
            return objectMapper.readValue(json, valueOfType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("readJson JsonProcessingException", e);
        }
    }
}
