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.Certificate;
import de.avatic.taric.model.MeasureSeries;
import de.avatic.taric.repository.CertificateRepository;
import de.avatic.taric.repository.MeasureSeriesRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MeasureSeriesReferenceSerializer extends JsonSerializer<AggregateReference<MeasureSeries, Integer>> {


    private final MeasureSeriesRepository measureSeriesRepository;

    public MeasureSeriesReferenceSerializer(MeasureSeriesRepository measureSeriesRepository) {

        this.measureSeriesRepository = measureSeriesRepository;
    }

    @Override
    public void serialize(AggregateReference<MeasureSeries, Integer> value, JsonGenerator gen, SerializerProvider serializer) throws IOException {
        if (value != null) {
            MeasureSeries series = measureSeriesRepository.findById(value.getId())
                    .orElse(null);

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

}
