package de.avatic.taric.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import de.avatic.taric.model.Footnote;
import de.avatic.taric.model.Geo;
import de.avatic.taric.repository.GeoRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GeoReferenceSerializer extends JsonSerializer<AggregateReference<Geo, Integer>> {

    private final GeoRepository geoRepository;

    public GeoReferenceSerializer(GeoRepository geoRepository) {
        this.geoRepository = geoRepository;
    }

    @Override
    public void serialize(AggregateReference<Geo, Integer> value, JsonGenerator gen, SerializerProvider serializer) throws IOException {

        if (value != null) {
            Geo geo = geoRepository.findById(value.getId()).orElse(null);

            gen.writeObject(geo);
        } else {
            gen.writeNull();
        }
    }
}
