package at.procon.eventhub.processing.service;

import at.procon.eventhub.dto.EventHubEventDto;
import at.procon.eventhub.processing.model.UnifiedRuntimeEventBundle;
import at.procon.eventhub.processing.model.UnifiedRuntimeProcessingRequest;
import at.procon.eventhub.processing.support.TachographRuntimeIdentityResolver;
import at.procon.eventhub.tachographfilesession.model.ResolvedDriverTimeline;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class UnifiedRuntimeDriverTimelineService {

    private final UnifiedRuntimeEventAssemblyService runtimeEventAssemblyService;
    private final UnifiedEventTimelineReconstructor timelineReconstructor;

    public UnifiedRuntimeDriverTimelineService(
            UnifiedRuntimeEventAssemblyService runtimeEventAssemblyService,
            UnifiedEventTimelineReconstructor timelineReconstructor
    ) {
        this.runtimeEventAssemblyService = runtimeEventAssemblyService;
        this.timelineReconstructor = timelineReconstructor;
    }

    public ResolvedDriverTimeline loadDriverTimeline(UnifiedRuntimeProcessingRequest request) {
        UnifiedRuntimeEventBundle bundle = runtimeEventAssemblyService.assembleDriverScopedEvents(request);
        return timelineReconstructor.reconstruct(
                null,
                resolveDriverKey(request, bundle.mergedEvents()),
                bundle.mergedEvents()
        );
    }

    private String resolveDriverKey(
            UnifiedRuntimeProcessingRequest request,
            List<EventHubEventDto> events
    ) {
        return TachographRuntimeIdentityResolver.requestDriverKey(request, events);
    }
}
