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

import java.io.IOException;

@Component
public class LegalBaseReferenceSerializer extends JsonSerializer<AggregateReference<Footnote, Integer>> {


    private final LegalBaseRepository legalBaseRepository;

    public LegalBaseReferenceSerializer(LegalBaseRepository legalBaseRepository) {
        this.legalBaseRepository = legalBaseRepository;
    }

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

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