package at.procon.eventhub.yellowfox.camel;

import at.procon.eventhub.dto.EventHubEventDto;
import at.procon.eventhub.yellowfox.dto.YellowFoxD8BookingDto;
import at.procon.eventhub.yellowfox.service.YellowFoxD8BookingEventMapper;
import at.procon.eventhub.yellowfox.service.YellowFoxD8IgnitionTransitionDetector;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class YellowFoxD8BookingInputRoute extends RouteBuilder {

    private final YellowFoxD8BookingEventMapper mapper;
    private final YellowFoxD8IgnitionTransitionDetector ignitionTransitionDetector;

    public YellowFoxD8BookingInputRoute(
            YellowFoxD8BookingEventMapper mapper,
            YellowFoxD8IgnitionTransitionDetector ignitionTransitionDetector
    ) {
        this.mapper = mapper;
        this.ignitionTransitionDetector = ignitionTransitionDetector;
    }

    @Override
    public void configure() {
        from("direct:yellowfox-d8-booking-input")
                .routeId("yellowfox-d8-booking-input-route")
                .process(exchange -> {
                    List<YellowFoxD8BookingDto> bookings = exchange.getMessage().getBody(List.class);
                    YellowFoxD8IgnitionTransitionDetector.Session ignitionSession = ignitionTransitionDetector.newSession(false);
                    List<EventHubEventDto> events = new ArrayList<>();
                    for (YellowFoxD8BookingDto booking : bookings) {
                        events.add(mapper.map(booking));
                        EventHubEventDto ignitionEvent = ignitionSession.detect(booking);
                        if (ignitionEvent != null) {
                            events.add(ignitionEvent);
                        }
                    }
                    exchange.getMessage().setBody(events);
                })
                .split(body())
                    .to("direct:eventhub-normalized-input")
                .end();
    }
}
