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

import java.io.IOException;

@Component
public class MonetaryUnitReferenceSerializer extends JsonSerializer<AggregateReference<MonetaryUnit, Integer>> {
    private final MonetaryUnitRepository monetaryUnitRepository;

    public MonetaryUnitReferenceSerializer(MonetaryUnitRepository monetaryUnitRepository) {
        this.monetaryUnitRepository = monetaryUnitRepository;
    }

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

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

}
