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.LegalBase;
import de.avatic.taric.model.Measure;
import de.avatic.taric.repository.MeasureRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MeasureReferenceSerializer extends JsonSerializer<AggregateReference<Measure, Integer>> {


    private final MeasureRepository measureRepository;

    public MeasureReferenceSerializer(MeasureRepository measureRepository) {
        this.measureRepository = measureRepository;
    }

    @Override
    public void serialize(AggregateReference<Measure, Integer> value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        if (value != null) {
            Measure measure = measureRepository.findById(value.getId())
                    .orElse(null);

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

}
