package be.iminds.ilabt.jfed.util;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * User: twalcari
 * Date: 7/15/2015
 * Time: 16:34
 */
public class GeniUrnTypeAdapter extends TypeAdapter<GeniUrn> {

    @Override
    public GeniUrn read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
        }
        String stringValue = reader.nextString();
        try {
            return new GeniUrn(stringValue);
        } catch (GeniUrn.GeniUrnParseException e) {
            throw new IOException("Invalid URN structure",e);
        }
    }

    @Override
    public void write(JsonWriter writer, GeniUrn value) throws IOException {
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.value(value.toString());
    }
}
