package at.procon.eventhub.tachographfilesession.model;

import at.procon.eventhub.dto.EventHubEventDto;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public record TachographTimelineEventBundle(
        List<EventHubEventDto> activityEvents,
        List<EventHubEventDto> vehicleUsageEvents,
        List<EventHubEventDto> supportEvents
) {
    public TachographTimelineEventBundle {
        activityEvents = copy(activityEvents);
        vehicleUsageEvents = copy(vehicleUsageEvents);
        supportEvents = copy(supportEvents);
    }

    public List<EventHubEventDto> allEvents() {
        List<EventHubEventDto> result = new ArrayList<>(activityEvents.size() + vehicleUsageEvents.size() + supportEvents.size());
        result.addAll(activityEvents);
        result.addAll(vehicleUsageEvents);
        result.addAll(supportEvents);
        result.sort(Comparator.comparing(EventHubEventDto::occurredAt)
                .thenComparing(event -> event.eventDomain().name())
                .thenComparing(event -> event.eventType().name())
                .thenComparing(event -> event.lifecycle().name())
                .thenComparing(EventHubEventDto::externalSourceEventId));
        return List.copyOf(result);
    }

    private static List<EventHubEventDto> copy(List<EventHubEventDto> events) {
        return events == null ? List.of() : List.copyOf(events);
    }
}
