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.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import classes.Position;

public class PositionAdapter implements JsonSerializer<Position>, JsonDeserializer<Position> {

	@Override
	public JsonElement serialize(Position arg0, Type arg1, JsonSerializationContext arg2) {
		// TODO Auto-generated method stub
		return new JsonPrimitive(arg0.x + ":" + arg0.y);
	}

	@Override
	public Position deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) {
		// TODO Auto-generated method stub
		try {
			String arg = arg0.getAsString();
			int mid = arg.indexOf(':');
			int x = Integer.parseInt(arg.substring(0, mid));
			int y = Integer.parseInt(arg.substring(mid + 1, arg.length()));
			return new Position(x, y);

		} catch (Exception e) {
			// TODO: handle exception
		}
		return new Position(-1, -1);
	}

}
