package at.procon.eventhub.processing.service;

import at.procon.eventhub.processing.model.UnifiedDriverTimelineRequest;
import at.procon.eventhub.processing.model.UnifiedEventSourceFamily;
import at.procon.eventhub.tachographfilesession.model.DriverExtractionSession;
import at.procon.eventhub.tachographfilesession.model.ResolvedDriverTimeline;
import at.procon.eventhub.tachographfilesession.model.TachographFileSession;
import at.procon.eventhub.tachographfilesession.service.DriverNotFoundInSessionException;
import at.procon.eventhub.tachographfilesession.service.EventBackedDriverTimelineBuilder;
import at.procon.eventhub.tachographfilesession.service.TachographFileSessionNotFoundException;
import at.procon.eventhub.tachographfilesession.service.TachographFileSessionRepository;
import org.springframework.stereotype.Component;

@Component
public class TachographFileSessionUnifiedDriverTimelineSource implements UnifiedDriverTimelineSource {

    private final TachographFileSessionRepository repository;
    private final EventBackedDriverTimelineBuilder eventBackedDriverTimelineBuilder;

    public TachographFileSessionUnifiedDriverTimelineSource(
            TachographFileSessionRepository repository,
            EventBackedDriverTimelineBuilder eventBackedDriverTimelineBuilder
    ) {
        this.repository = repository;
        this.eventBackedDriverTimelineBuilder = eventBackedDriverTimelineBuilder;
    }

    @Override
    public boolean supports(UnifiedDriverTimelineRequest request) {
        return request.sourceFamily() == UnifiedEventSourceFamily.TACHOGRAPH_FILE_SESSION;
    }

    @Override
    public ResolvedDriverTimeline loadDriverTimeline(UnifiedDriverTimelineRequest request) {
        TachographFileSession session = repository.find(request.sessionId())
                .orElseThrow(() -> new TachographFileSessionNotFoundException(request.sessionId()));
        DriverExtractionSession driver = session.driversByKey().get(request.driverKey());
        if (driver == null) {
            throw new DriverNotFoundInSessionException(request.sessionId(), request.driverKey());
        }
        return eventBackedDriverTimelineBuilder.build(session, driver);
    }
}
