package eu.dnetlib.pace.model;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

/**
 * The Class MapDocumentSerializer.
 */
public class RootMapDocumentSerializer implements InstanceCreator<RootMapDocument> {

	@Override
	public RootMapDocument createInstance(final Type type) {
		return new RootMapDocument();
	}

	/**
	 * Decode.
	 *
	 * @param bytes
	 *            the bytes
	 * @return the map document
	 */
	public static RootMapDocument decode(final byte[] bytes) {

		final GsonBuilder gson = new GsonBuilder();

		gson.registerTypeAdapter(Field.class, new JsonDeserializer<Field>() {

			@Override
			public Field deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
				final FieldListImpl fl = new FieldListImpl();
				if (json.isJsonObject()) {
					final String name = json.getAsJsonObject().get("name").getAsString();
					final String type = json.getAsJsonObject().get("type").getAsString();
					final String value = json.getAsJsonObject().get("value").getAsString();
					fl.add(new FieldValueImpl(eu.dnetlib.pace.config.Type.valueOf(type), name, value));
				}
				return fl;
			}
		});

		return gson.create().fromJson(new String(bytes), RootMapDocument.class);
	}

	/**
	 * To string.
	 *
	 * @param doc
	 *            the doc
	 * @return the string
	 */
	public static String toString(final RootMapDocument doc) {
		return new Gson().toJson(doc);
	}

	/**
	 * To byte array.
	 *
	 * @param doc
	 *            the doc
	 * @return the byte[]
	 */
	public static byte[] toByteArray(final RootMapDocument doc) {
		return toString(doc).getBytes();
	}

}
