package li.cil.oc2.common.serialization.ceres;

import com.google.gson.Gson;
import li.cil.ceres.api.DeserializationVisitor;
import li.cil.ceres.api.SerializationException;
import li.cil.ceres.api.SerializationVisitor;
import li.cil.ceres.api.Serializer;
import li.cil.oc2.common.vm.terminal.Terminal;
import org.jetbrains.annotations.Nullable;

public class ColorDataSerializer implements Serializer<Terminal.ColorData> {
    @Override
    public void serialize(final SerializationVisitor serializationVisitor, final Class<Terminal.ColorData> aClass, final Object o) throws SerializationException {
        final String json = new Gson().toJson(o);
        serializationVisitor.putObject("value", String.class, json);
    }

    @Override
    public Terminal.ColorData deserialize(final DeserializationVisitor deserializationVisitor, final Class<Terminal.ColorData> aClass, @Nullable final Object o) throws SerializationException {
        if (!deserializationVisitor.exists("value")) {
            return new Terminal.ColorData();
        }

        final String json = (String) deserializationVisitor.getObject("value", String.class, null);
        if (json == null) {
            return new Terminal.ColorData();
        }

        return new Gson().fromJson(json, Terminal.ColorData.class);
    }
}
