package com.thinkunion.park.service.common.iot.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.thinkunion.park.service.common.iot.capability.device.discovery.DiscoveryResponsePayload;
import com.thinkunion.park.service.common.iot.capability.device.payload.CommonRequestPayload;
import com.thinkunion.park.service.common.iot.capability.device.payload.KeyValuePair;
import com.thinkunion.park.service.common.iot.capability.device.payload.ValueWrapper;
import com.thinkunion.park.service.common.iot.capability.devicemodel.DataType;
import com.thinkunion.park.service.common.iot.capability.devicemodel.Service;

import java.lang.reflect.Type;

public class ModelGsonUtils {

    protected static Gson getGson() {
        return new GsonBuilder().setLenient().disableHtmlEscaping()
                .registerTypeAdapter((DataType.class), new DataType.DataTypeJsonSerializer())
                .registerTypeAdapter((DataType.class), new DataType.DataTypeJsonDeSerializer())
                .registerTypeAdapter((KeyValuePair.class), new KeyValuePair.KeyValuePairJsonDeSerializer())
                .registerTypeAdapter((KeyValuePair.class), new KeyValuePair.KeyValuePairJsonSerializer())
                .registerTypeAdapter((ValueWrapper.class), new ValueWrapper.ValueWrapperJsonSerializer())
                .registerTypeAdapter((ValueWrapper.class), new ValueWrapper.ValueWrapperJsonDeSerializer())
                .registerTypeAdapter((DiscoveryResponsePayload.DiscoveryResponseData.class),
                        new DiscoveryResponsePayload.DiscoveryResponseDataDeserializer())
                .registerTypeAdapter((CommonRequestPayload.class),
                        new CommonRequestPayload.CommonRequestPayloadJsonDeSerializer())
                .registerTypeAdapter((Service.class), new Service.ServiceJsonDeSerializer()).create();
    }

    public static <T> T fromJson(String json, Gson gson, Type type) {
        try {
            return gson.fromJson(json, type);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> String toJson(T t, Gson gson) {
        if (gson == null) {
            gson = ModelGsonUtils.getGson();
        }
        String ret = null;
        try {
            ret = gson.toJson(t, new TypeToken<T>() {
            }.getType());
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static <T> T fromJson(String json, Type type) {
        return ModelGsonUtils.fromJson(json, ModelGsonUtils.getGson(), type);
    }

    public static <T> String toJson(T t) {
        return ModelGsonUtils.toJson(t, ModelGsonUtils.getGson());
    }

}

