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

import java.io.IOException;

@Component
public class ConditionTypeReferenceSerializer extends JsonSerializer<AggregateReference<ConditionType, Integer>> {


    private final ConditionTypeRepository conditionTypeRepository;

    public ConditionTypeReferenceSerializer(ConditionTypeRepository conditionTypeRepository) {
        this.conditionTypeRepository = conditionTypeRepository;
    }

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

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

}
