package eu.dnetlib.espas.dm.local;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

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

public class GsonUtils {

	public static Gson createGson() {
		JsonSerializer<Date> ser = new JsonSerializer<Date>() {

			@Override
			public JsonElement serialize(Date src, Type typeOfSrc,
					JsonSerializationContext context) {
				return src == null ? null : new JsonPrimitive(src.getTime());
			}

		};

		JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
			@Override
			public Date deserialize(JsonElement json, Type typeOfT,
					JsonDeserializationContext context)
					throws JsonParseException {
				return json == null ? null : new Date(json.getAsLong());
			}
		};

		JsonSerializer<String> sser = new JsonSerializer<String>() {

			@Override
			public JsonElement serialize(String s, Type typeOfScr,
					JsonSerializationContext context) {
				try {
					return s == null ? null : new JsonPrimitive(
							URLEncoder.encode(s, "utf-8"));
				} catch (UnsupportedEncodingException e) {
				}

				return null;
			}
		};

		JsonDeserializer<String> sdeser = new JsonDeserializer<String>() {

			@Override
			public String deserialize(JsonElement json, Type typeOfSrc,
					JsonDeserializationContext context)
					throws JsonParseException {
				try {
					return json == null ? null : URLDecoder.decode(
							json.getAsString(), "utf-8");
				} catch (UnsupportedEncodingException e) {
				}
				;

				return null;
			}
		};

		Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, ser)
				.registerTypeAdapter(Date.class, deser)
				.registerTypeAdapter(String.class, sser)
				.registerTypeAdapter(String.class, sdeser).create();

		return gson;
	}
}