package at.procon.eventhub.tachographfilesession.service;

import at.procon.eventhub.processing.service.UnifiedEventTimelineReconstructor;
import at.procon.eventhub.tachographfilesession.model.DriverExtractionSession;
import at.procon.eventhub.tachographfilesession.model.ExtractionWarning;
import at.procon.eventhub.tachographfilesession.model.ResolvedDriverTimeline;
import at.procon.eventhub.tachographfilesession.model.TachographFileSession;
import at.procon.eventhub.tachographfilesession.model.TachographTimelineEventBundle;
import java.util.LinkedHashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class EventBackedDriverTimelineBuilder {

    private final DriverTimelineEventBuilder eventBuilder;
    private final UnifiedEventTimelineReconstructor timelineReconstructor;

    public EventBackedDriverTimelineBuilder(DriverTimelineEventBuilder eventBuilder) {
        this(eventBuilder, new UnifiedEventTimelineReconstructor());
    }

    @Autowired
    public EventBackedDriverTimelineBuilder(
            DriverTimelineEventBuilder eventBuilder,
            UnifiedEventTimelineReconstructor timelineReconstructor
    ) {
        this.eventBuilder = eventBuilder;
        this.timelineReconstructor = timelineReconstructor;
    }

    public ResolvedDriverTimeline build(
            TachographFileSession session,
            DriverExtractionSession driverSession
    ) {
        TachographTimelineEventBundle bundle = eventBuilder.buildEventBundle(session, driverSession);
        return timelineReconstructor.reconstruct(
                session.sessionId(),
                driverSession.driverKey(),
                bundle.allEvents(),
                mergeWarnings(session.warnings(), driverSession.warnings()),
                fallbackSourceKind(session)
        );
    }

    private List<ExtractionWarning> mergeWarnings(List<ExtractionWarning> sessionWarnings, List<ExtractionWarning> driverWarnings) {
        LinkedHashSet<ExtractionWarning> merged = new LinkedHashSet<>();
        if (sessionWarnings != null) {
            merged.addAll(sessionWarnings);
        }
        if (driverWarnings != null) {
            merged.addAll(driverWarnings);
        }
        return List.copyOf(merged);
    }

    private String fallbackSourceKind(TachographFileSession session) {
        return session.metadata().driverCardFile() ? "DRIVER_CARD" : "VEHICLE_UNIT";
    }
}
