package at.procon.eventhub.camel;

import at.procon.eventhub.dto.EventHubEventDto;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.Exchange;
import org.springframework.stereotype.Component;

@Component
public class EventHubEventAggregationStrategy implements AggregationStrategy {

    @Override
    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        EventHubEventDto event = newExchange.getMessage().getBody(EventHubEventDto.class);
        if (oldExchange == null) {
            List<EventHubEventDto> events = new ArrayList<>();
            events.add(event);
            newExchange.getMessage().setBody(events);
            return newExchange;
        }

        @SuppressWarnings("unchecked")
        List<EventHubEventDto> events = oldExchange.getMessage().getBody(List.class);
        events.add(event);
        return oldExchange;
    }
}
