package at.procon.eventhub.yellowfox.service;

import at.procon.eventhub.dto.EventHubEventDto;
import at.procon.eventhub.yellowfox.dto.YellowFoxD8BookingDto;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component
public class YellowFoxD8IgnitionTransitionDetector {

    private final YellowFoxD8BookingEventMapper mapper;

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

    public Session newSession(boolean emitInitialSnapshot) {
        return new Session(mapper, emitInitialSnapshot);
    }

    public static class Session {
        private final YellowFoxD8BookingEventMapper mapper;
        private final boolean emitInitialSnapshot;
        private final Map<String, Integer> lastIgnitionByVehicle = new HashMap<>();

        private Session(YellowFoxD8BookingEventMapper mapper, boolean emitInitialSnapshot) {
            this.mapper = mapper;
            this.emitInitialSnapshot = emitInitialSnapshot;
        }

        public EventHubEventDto detect(YellowFoxD8BookingDto booking) {
            if (booking == null || booking.ignition() == null || booking.vehicleRef() == null || !booking.vehicleRef().hasAnyReference()) {
                return null;
            }
            String vehicleKey = booking.vehicleRef().stableKey();
            Integer previous = lastIgnitionByVehicle.put(vehicleKey, booking.ignition());
            if (previous == null) {
                previous = booking.previousIgnition();
                if (previous == null) {
                    return emitInitialSnapshot ? mapper.mapIgnitionTransition(booking, null) : null;
                }
            }
            if (!previous.equals(booking.ignition())) {
                return mapper.mapIgnitionTransition(booking, previous);
            }
            return null;
        }
    }
}
