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

import java.io.IOException;

@Component
public class MeasureActionReferenceSerializer extends JsonSerializer<AggregateReference<MeasureAction, Integer>> {


    private final MeasureActionRepository measureActionRepository;

    public MeasureActionReferenceSerializer(MeasureActionRepository measureActionRepository) {


        this.measureActionRepository = measureActionRepository;
    }

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

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

}
