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

import java.io.IOException;

@Component
public class UnitReferenceSerializer  extends JsonSerializer<AggregateReference<Unit, Integer>> {
    private final UnitRepository unitRepository;

    public UnitReferenceSerializer(UnitRepository unitRepository) {
        this.unitRepository = unitRepository;
    }

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

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

}
