package com.ericsson.uecontrol.core.util;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;

public class AbstractElementAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> {
    private static final String CLASS_FIELD = "@class";
    private static final String PROPERTIES_FIELD = "@properties";

    @Override
    public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add(CLASS_FIELD, new JsonPrimitive(src.getClass().getName()));
        result.add(PROPERTIES_FIELD, context.serialize(src, src.getClass()));

        return result;
    }

    @Override
    public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String type = jsonObject.get(CLASS_FIELD).getAsString();
        JsonElement element = jsonObject.get(PROPERTIES_FIELD);

        try {
            return context.deserialize(element, Class.forName(type));
        } catch (ClassNotFoundException e) {
            throw new JsonParseException("Unknown class: " + type, e);
        }
    }
}