package TypeAdapter;

import java.lang.reflect.Type;

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 classes.AbstractCpsObject;
import classes.HolonSwitch;
import ui.controller.StoreController;

public class AbstractCpsObjectAdapter
		implements JsonSerializer<AbstractCpsObject>, JsonDeserializer<AbstractCpsObject> {

	@Override
	public JsonElement serialize(AbstractCpsObject arg0, Type arg1, JsonSerializationContext arg2) {
		// TODO Auto-generated method stub
		JsonObject object = new JsonObject();
		object.add("type", new JsonPrimitive(arg0.getClass().getSimpleName()));
		object.add("properties", arg2.serialize(arg0, arg0.getClass()));
		return object;
	}

	@Override
	public AbstractCpsObject deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
			throws JsonParseException {
		// TODO Auto-generated method stub
		JsonObject object = arg0.getAsJsonObject();
		String type = object.get("type").getAsString();
		JsonElement element = object.get("properties");
		try {
			String packageName = "classes.";
			return arg2.deserialize(element, Class.forName(packageName + type));
		} catch (ClassNotFoundException cnfe) {
			// TODO: handle exception
			throw new JsonParseException("Unknown element type: " + type, cnfe);
		}

	}

}
