diff --git a/ass2-service/trip/src/main/java/dst/ass2/service/trip/impl/TripService.java b/ass2-service/trip/src/main/java/dst/ass2/service/trip/impl/TripService.java index 230c32d..bce98c0 100644 --- a/ass2-service/trip/src/main/java/dst/ass2/service/trip/impl/TripService.java +++ b/ass2-service/trip/src/main/java/dst/ass2/service/trip/impl/TripService.java @@ -6,12 +6,16 @@ import dst.ass2.service.api.match.IMatchingService; import dst.ass2.service.api.trip.*; import javax.annotation.Resource; +import javax.inject.Named; import javax.inject.Singleton; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; +import java.util.ArrayList; import java.util.Date; +import java.util.List; +@Named("ITripService") @Singleton public class TripService implements ITripService { @PersistenceContext @@ -82,13 +86,10 @@ public class TripService implements ITripService { IMatch newMatch; try { trip = getTrip(tripId); - if (trip.getState() != TripState.CREATED) - throw new IllegalStateException("Trip is not in CREATED state"); - IDriver driver = getDriver(match.getDriverId()); IMatchDAO matchDAO = daoFactory.createMatchDAO(); for (IMatch m : matchDAO.findAll()) { - if (m.getDriver().getId().equals(driver.getId())) + if (m.getDriver() != null && m.getDriver().getId().equals(driver.getId())) throw new DriverNotAvailableException("Driver with id " + driver.getId() + " is already busy"); } @@ -133,6 +134,7 @@ public class TripService implements ITripService { // Set trip and tripInfo tripInfo.setTrip(trip); trip.setTripInfo(tripInfo); + trip.setState(TripState.COMPLETED); entityManager.persist(tripInfo); entityManager.merge(trip); } @@ -140,12 +142,38 @@ public class TripService implements ITripService { @Transactional @Override public void cancel(Long tripId) throws EntityNotFoundException { - + ITrip trip = getTrip(tripId); + trip.setState(TripState.CANCELLED); + entityManager.merge(trip); } + @Transactional @Override public boolean addStop(TripDTO trip, Long locationId) throws EntityNotFoundException, IllegalStateException { - return false; + ITrip savedTrip = getTrip(trip.getId()); + if (savedTrip.getState() != TripState.CREATED) + throw new IllegalStateException("Trip with id " + trip.getId() + " is not in CREATED state"); + getLocation(locationId); + + List stops = trip.getStops(); + if (stops.contains(locationId)) + return false; + // Add the stop + stops.add(locationId); + // Estimate fare (set to null if failed) + try { + trip.setFare(matchingService.calculateFare(trip)); + } catch (InvalidTripException e) { + trip.setFare(null); + } + ILocationDAO locationDAO = daoFactory.createLocationDAO(); + List locations = new ArrayList<>(); + for (Long location : trip.getStops()) { + locations.add(locationDAO.findById(location)); + } + savedTrip.setStops(locations); + entityManager.merge(savedTrip); + return true; } @Override