Files
sumoc-backend/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java
T

56 lines
2.2 KiB
Java

package SuMoC.backend.regulartrip.services;
import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
import SuMoC.backend.regulartrip.detectionapproaches.Detector;
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
import SuMoC.backend.trip.Modality;
import SuMoC.backend.trip.TripMapper;
import SuMoC.backend.trip.TripRepository;
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
import org.springframework.stereotype.Service;
import java.time.DayOfWeek;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class RegularTripDetectionService {
RegularTripDetectionProperties properties;
TripRepository tripRepository;
TripMapper tripMapper;
Detector tripDetector;
/**
* Detects regular trips for the current day of the week for all users based on saved trip data and RegularTripDetectionProperties.
* This is the main method that orchestrates the detection process and should be used to detect trips
* we want to suggest alternatives for.
*/
public HashMap<Long, List<DetectedRegularTripDTO>> detectRegularCarTripsByUserForDayOfWeek(DayOfWeek dayOfWeek) {
var tripsByUser = getTripsByUser(Modality.CAR, dayOfWeek);
HashMap<Long, List<DetectedRegularTripDTO>> results = new HashMap<>();
for (Long userId : tripsByUser.keySet()) {
results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId)));
}
return results;
}
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality, DayOfWeek dayOfWeek) {
Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(fromDate, modality, dayOfWeek));
HashMap<Long, List<RegularTripDetectionDTO>> tripsByUser = new HashMap<>();
for (RegularTripDetectionDTO dto : dtoList) {
tripsByUser.computeIfAbsent(dto.getUserId(), k -> new ArrayList<>()).add(dto);
}
return tripsByUser;
}
}