/*
 * *************************************************
 * Copyright (c) 2018 QMTH. All Rights Reserved.
 * Created by Deason on 2018-07-12 15:31:09.
 * *************************************************
 */

package cn.com.qmth.examcloud.core.questions.base.converter.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简单封装Jackson，实现JSON 与 Java Object互相转换的Mapper
 * 封装不同的输出风格, 使用不同的builder函数创建实例
 */
@SuppressWarnings("unchecked")
public class JsonMapper {
    private static Logger log = LoggerFactory.getLogger(JsonMapper.class);
    private ObjectMapper mapper;

    public JsonMapper() {
        this(null);
    }

    public JsonMapper(Include include) {
        mapper = new ObjectMapper();
        //设置输出时包含属性的风格
        if (include != null) {
            mapper.setSerializationInclusion(include);
        }
        //设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    /**
     * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用
     */
    public static JsonMapper nonEmptyMapper() {
        return new JsonMapper(Include.NON_EMPTY);
    }

    public static JsonMapper nonNullMapper() {
        return new JsonMapper(Include.NON_NULL);
    }

    /**
     * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式，建议在内部接口中使用
     */
    public static JsonMapper nonDefaultMapper() {
        return new JsonMapper(Include.NON_DEFAULT);
    }

    /**
     * Object可以是POJO，也可以是Collection或数组
     * 如果对象为Null, 返回"null"
     * 如果集合为空集合, 返回"[]"
     */
    public String toJson(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            log.error("write to json string error:" + object);
            return null;
        }
    }

    /**
     * 反序列化POJO或简单Collection如List<String>
     * 如果JSON字符串为Null或"null"字符串, 返回Null
     * 如果JSON字符串为"[]", 返回空集合
     * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType)
     */
    public <T> T fromJson(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            return mapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            log.error("parse json string error", e);
            return null;
        }
    }

    /**
     * 反序列化复杂Collection如List<Bean>, 先使用createCollectionType()或constructMapType()构造类型, 然后调用本函数
     */
    public <T> T fromJson(String jsonString, JavaType javaType) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            return (T) mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            log.error("parse json string error", e);
            return null;
        }
    }

    /**
     * 反序列化复杂的对象，如Page<Bean>
     */
    public <T> T fromJson(String jsonString, TypeReference javaType) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            return (T) mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            log.error("parse json string error", e);
            return null;
        }
    }

    /**
     * json to list
     */
    public <T> List<T> toList(String jsonString, Class<T> bean) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            JavaType javaType = constructCollectionType(List.class, bean);
            return mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            log.error("parse json string error", e);
            return null;
        }
    }

    /**
     * json to simple HashMap
     */
    public <T> Map<String, T> toHashMap(String jsonString, Class<T> bean) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            JavaType javaType = constructMapType(HashMap.class, String.class, bean);
            return mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            log.error("parse json string error:", e);
            return null;
        }
    }

    /**
     * 构造Collection类型
     */
    public JavaType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
        return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
    }

    /**
     * 构造Map类型
     */
    public JavaType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
        return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
    }

    /**
     * 当JSON里只含有Bean的部分屬性時，更新一個已存在Bean，只覆盖該部分的屬性
     */
    public void update(String jsonString, Object object) {
        try {
            mapper.readerForUpdating(object).readValue(jsonString);
        } catch (JsonProcessingException e) {
            log.error("update json string:" + jsonString + " to object:" + object + " error.");
        } catch (IOException e) {
            log.error("update json string:" + jsonString + " to object:" + object + " error.");
        }
    }

    /**
     * 輸出JSONP格式数据
     */
    public String toJsonP(String functionName, Object object) {
        return toJson(new JSONPObject(functionName, object));
    }

    /**
     * 設定是否使用Enum的toString函數來读写Enum
     * 為False時使用Enum的name()函數來读写Enum, 默認為False
     * 注意本函數一定要在Mapper創建後, 所有的读写動作之前調用
     */
    public void enableEnumUseToString() {
        mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
    }

    /**
     * 取出Mapper做进一步的设置或使用其他序列化API
     */
    public ObjectMapper getMapper() {
        return mapper;
    }

    /***
     * 把Json字符串转换成Node对象
     */
    public JsonNode getNode(String jsonStr) {
        try {
            //mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            return mapper.readTree(jsonStr);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

}