Package at.fhj.itm.beans

Source Code of at.fhj.itm.beans.SearchTrip$RouteInfo

package at.fhj.itm.beans;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import org.apache.log4j.Logger;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;

import at.fhj.itm.business.ServiceAssembler;
import at.fhj.itm.business.ServiceTrip;
import at.fhj.itm.model.Location;
import at.fhj.itm.model.Trip;
import at.fhj.itm.model.User;
import at.fhj.itm.model.Waypoint;
import at.fhj.itm.util.EmailUtil;
import at.fhj.itm.util.EmailUtilImpl;
import at.fhj.itm.util.JsfUtil;
import at.fhj.itm.util.PDFUtil;
import at.fhj.itm.util.comparator.RouteInfoFromAscComparator;
import at.fhj.itm.util.comparator.RouteInfoFromDescComparator;
import at.fhj.itm.util.comparator.RouteInfoTimeAscComparator;
import at.fhj.itm.util.comparator.RouteInfoTimeDescComparator;
import at.fhj.itm.util.comparator.RouteInfoToAscComparator;
import at.fhj.itm.util.comparator.RouteInfoToDescComparator;

/**
* The Bean used by the Trip-Search (searchTrips.xhtml, foundTrips.xhtml)<br>
* It offers the method getMatches which will find and cache Route Information
* that matches the data given. This data is <code>from</code> and
* <code>to</code> which are Strings representing a City or Address. The third
* attribute is a date, which has the current date as default.<br>
* <br>
* The RouteInformation provides methods to access the required values. It
* mostly delegates to the Entity that stores that data, but it also provides
* methods for actions and does some calculations, for example the available
* seats.
*
*
* @author Christian Tassler
* @author Martin Buchmayr
* @author Patrick Winkelmayer
* @author Gerald Reisinger
*
*/

@ManagedBean
@SessionScoped
public class SearchTrip implements LoginListener {
  private final Logger logger = Logger.getLogger(Login.class);

  /* Attributes for the search */
  private String from;
  private String to;
  private Calendar date = new GregorianCalendar();
  private boolean leaveTime = true;
  private boolean self = false;
  private boolean visiblePDFButton = false;
  private String sortMethod = "none";
  private String driver = "";
  private DefaultStreamedContent pdfFile;

  /* Attributes for the details */
  private List<RouteInfo> matches;
  private RouteInfo selectedTrip;

  /* Attributes changeable by constructor for testing */
  private final JsfUtil jsfUtil;

  private ServiceTrip tripService;

  /* this format is used to pass it in the url */
  private DateFormat dateFormat4URL = DateFormat.getDateTimeInstance(
      DateFormat.SHORT, DateFormat.SHORT, Locale.GERMAN);

  private InputStream pdf;

  /**
   * The default Constructor
   */
  public SearchTrip() {
    this(ServiceAssembler.getInstance().createJsfUtil(), ServiceAssembler
        .getInstance().createServiceTrip());
  }

  /**
   * A Constructor to replace the jsfUtils and the DAOs for testing purposes
   *
   * @param jsfUtils
   * @param tripDao
   * @param waypointDao
   * @param pointDAO
   */
  protected SearchTrip(JsfUtil jsfUtils, ServiceTrip tripService) {
    this.jsfUtil = jsfUtils;

    setDate(new Date());
    setTripService(tripService);
    this.jsfUtil.addLoginListener(this);
  }

  /*
   * Getter and Setter
   */

  /**
   * @return returns the city from where to go
   */
  public String getFrom() {
    return from;
  }

  /**
   * @return services to modify a trip
   */
  public final ServiceTrip getTripService() {
    return tripService;
  }

  /**
   * @param tripService
   *            sets a service for modifying trips
   */
  public final void setTripService(ServiceTrip tripService) {
    this.tripService = tripService;
  }

  /**
   * @param from
   *            sets city to go from
   */
  public void setFrom(String from) {
    clearCache();
    this.from = from;
  }

  /**
   * @return returns city to go to
   */
  public String getTo() {
    return to;
  }

  /**
   * @param to
   *            sets city to go to
   */
  public void setTo(String to) {
    clearCache();
    this.to = to;
  }

  public boolean isSelf() {
    return self;
  }

  public void setSelf(boolean self) {
    clearCache();
    this.self = self;
  }

  /**
   * The usage of the time is dependend whether it is the leaveTime or the
   * arriving time (see {@link #isLeaveTime()}).
   *
   * @return Date
   */
  public Date getDate() {
    return date.getTime();
  }

  public void setDate(Date date) {
    clearCache();
    if (date == null)
      date = new Date();
    this.date.setTime(date);
  }

  /**
   * Returns the time in the format hh:mm e.g. 23:01
   *
   * @return the time hh:mm
   */
  public String getTime() {
    return jsfUtil.getSimpleTime().format(getDate());
  }

  /**
   * @param time
   *            set time in format hh:mm e.g. 23:01
   */
  public void setTime(String time) {
    clearCache();
    if (!time.matches("\\d\\d:\\d\\d"))
      return;
    String[] values = time.split(":");
    int hh = Integer.parseInt(values[0]);
    int mm = Integer.parseInt(values[1]);
    if (hh > 23)
      hh = 0;
    if (mm > 59)
      mm = 0;
    this.date.set(Calendar.HOUR_OF_DAY, hh);
    this.date.set(Calendar.MINUTE, mm);
  }

  /**
   * @return specifies if the time is the time to leave or arrive
   */
  public boolean isLeaveTime() {
    return leaveTime;
  }

  /**
   * @param leaveTime
   *            boolean to specify if the time is the time to leave or arrive
   */
  public void setLeaveTime(boolean leaveTime) {
    clearCache();
    this.leaveTime = leaveTime;
  }

  /*
   * Additional Getter Setter for convenience
   */

  /**
   * Sets the date and the leave or arrive at flag
   */
  protected void setArriveAt(String arriveAt) throws ParseException {
    clearCache();
    setDate(getDateFormatForURL().parse(arriveAt));
    setLeaveTime(false);
  }

  /**
   * Sets the date and the leave or arrive at flag
   */
  protected void setLeaveAt(String leaveAt) throws ParseException {
    clearCache();
    setDate(getDateFormatForURL().parse(leaveAt));
    setLeaveTime(true);
  }

  /**
   * Checks if Routes are found.
   *
   * @return true if at least one Route has been found.
   */
  public boolean getHasFound() {
    return !getMatches().isEmpty();
  }

  /**
   * Checks if a user is logged in.
   *
   * @return true if a user is logged in.
   */
  public boolean isLoggedIn() {
    return getLoggedInUser() != null;
  }

  private User loggedInUser;

  /**
   * @return the logged in user or null.
   */
  private User getLoggedInUser() {
    return loggedInUser;
  }

  /**
   * @param routeInfo
   *            the selectedTrip to set
   */
  public void setSelectedTrip(RouteInfo routeInfo) {
    clearCache();
    this.selectedTrip = routeInfo;
  }

  /**
   * @return the selectedTrip
   */
  public RouteInfo getSelectedTrip() {
    return selectedTrip;
  }

  /**
   * @return the dateformat used to pass the date in the url
   */
  public DateFormat getDateFormatForURL() {
    return dateFormat4URL;
  }

  /**
   * The matching trips will be found using {@link #findMatches()}
   *
   * @return List of Trips
   */
  public List<RouteInfo> getMatches() {
    if (matches == Collections.EMPTY_LIST)
      matches = findMatches();
    return matches;
  }

  /**
   * @return the sortMethod
   */
  public String getSortMethod() {
    return sortMethod;
  }

  /**
   * @param sets
   *            the desires sort method
   */
  public void setSortMethod(String sortMethod) {
    clearCache();
    this.sortMethod = sortMethod;
  }

  /**
   * @return the driver
   */
  public String getDriver() {
    return driver;
  }

  /**
   * @param set
   *            the driver the user is searching for
   */
  public void setDriver(String driver) {
    clearCache();
    this.driver = driver;
  }

  /**
   * Any valid value will overwrite the current field.<br>
   *
   * @param params
   *            Map<String, String> where the key is the fields representation
   */
  private void setAllFromMap(Map<String, String> params) {
    String self = params.get("self");
    if (self != null)
      this.setSelf(true);
    else
      this.setSelf(false);

    String to = params.get("to");
    if (to != null) {
      this.setTo(to);
    }
    else {
      this.setTo(null);
    }
    String from = params.get("from");
    if (from != null) {
      this.setFrom(from);
    }
    else {
      this.setFrom(null);
    }
    String leaveAt = params.get("leaveAt");
    if (leaveAt != null) {
      try {
        this.setLeaveAt(leaveAt);
      } catch (ParseException e) {
        // the values will be validated later
      }
    }
   
    String arriveAt = params.get("arriveAt");
    if (arriveAt != null) {
      try {
        this.setArriveAt(arriveAt);
      } catch (ParseException e) {
        // the values will be validated later
      }
    }
     

    String sortMethod = params.get("sort");
    if (sortMethod != null) {
      if (!sortMethod.equals("none")) {
        if (sortMethod.equals("timeASC")) {
          this.setSortMethod(sortMethod);
        } else if (sortMethod.equals("timeDESC")) {
          this.setSortMethod(sortMethod);
        } else if (sortMethod.equals("fromASC")) {
          this.setSortMethod(sortMethod);
        } else if (sortMethod.equals("toASC")) {
          this.setSortMethod(sortMethod);
        } else {
          this.setSortMethod("none");
        }
      }
    }
    String driver = params.get("driver");
    if (driver != null) {
      this.setDriver(driver);
    }
    else {
      this.setDriver(null);
    }

  }

  /**
   * Translates the fields to a readable GET-Url.
   *
   * @return url with GET request
   */
  protected String getAllInSearchUrl() {
    if (!validFields())
      throw new IllegalArgumentException("Input is not valid");

    StringBuilder sb = new StringBuilder();
    sb.append("./foundTrips.jsf");
    sb.append("?from=").append(getFrom());
    sb.append("&to=").append(getTo());
    if (this.isLeaveTime())
      sb.append("&leaveAt=").append(
          getDateFormatForURL().format(getDate()));
    else
      sb.append("&arriveAt=").append(
          getDateFormatForURL().format(getDate()));
    sb.append("&sort=").append(getSortMethod());
    sb.append("&driver=").append(getDriver());
    return sb.toString();
  }

  /*
   * Logic
   */

  /**
   * After checking the get-url for parameter it will call the DAO for all
   * Trips. With the values of this beans fields it filters out the
   * non-matching Trips. The resulting Trips are packed into
   * RouteInfo-Objects.
   *
   * @return List of RouteInfos
   */
  public List<RouteInfo> findMatches() {
    // any valid data given in the get-params are overwriting the current
    // data
    clearCache();
    Map<String, String> params = jsfUtil.getRequestParameterMap();

    setAllFromMap(params);
    setVisiblePDFButton(true);
    // validate input
    if (!isSelf()) {
      if (!validFields())
        return Collections.emptyList();
    }

    // DB select
    List<Trip> trips = new ArrayList<Trip>();
    if (this.isSelf()) {
      clearCache();
      if (getLoggedInUser() != null) {
        trips = getTripService().allBookedTripsByUser(
            this.jsfUtil.getLoggedInUser().getId());
        //trips = Collections.EMPTY_LIST;
      }
    } else if (!driver.isEmpty()) {
      trips = getTripService().searchTrip(from, to, driver);
    } else {
      trips = getTripService().searchTrip(getFrom(), getTo());
    }

    if (trips.isEmpty()) {
      return Collections.emptyList();
    }

    // pack Trips into RouteInfo Objects
    List<RouteInfo> routeInfos = new ArrayList<SearchTrip.RouteInfo>();

    for (Trip t : trips) {
      routeInfos.add(new RouteInfo(t));
    }

    // sort the map according to the sort method
    if (!sortMethod.equals("none")) {
      if (sortMethod.equals("timeASC")) {
        Collections.sort(routeInfos, new RouteInfoTimeAscComparator());
      } else if (sortMethod.equals("timeDESC")) {
        Collections.sort(routeInfos, new RouteInfoTimeDescComparator());
      } else if (sortMethod.equals("fromASC")) {
        Collections.sort(routeInfos, new RouteInfoFromAscComparator());
      } else if (sortMethod.equals("fromDESC")) {
        Collections.sort(routeInfos, new RouteInfoFromDescComparator());
      } else if (sortMethod.equals("toASC")) {
        Collections.sort(routeInfos, new RouteInfoToAscComparator());
      } else if (sortMethod.equals("toDESC")) {
        Collections.sort(routeInfos, new RouteInfoToDescComparator());
      }
    }

    // mark trips which are booked
    if (getLoggedInUser() != null) {
      checkRoutesUserWaypoints(routeInfos);
    }

    setSelectedTrip(routeInfos.get(0));
    return routeInfos;
  }

  /**
   * Compares all Waypoints of all Trips in all passed Routes with the Users
   * Waypoints and sets those Waypoints from the User to the Users Waypoint
   * stored in the Route. If the Route has no matching Waypoint, a new one is
   * used which means the Route has not been booked.
   *
   * @param routeInfos
   *            List of RouteInfos
   */
  private void checkRoutesUserWaypoints(List<RouteInfo> routeInfos) {
    if (getLoggedInUser() == null)
      return;

    List<Waypoint> userWaypoints = getTripService().getWaypointsForUser(
        getLoggedInUser());

    for (RouteInfo route : routeInfos) {
      route.checkUserWaypoints(userWaypoints);
    }
  }

  /**
   * The matching Trip-list has to be cached, therefore it needs to be cleared
   * whenever a field changes.
   */
  protected void clearCache() {
    matches = Collections.emptyList();
   
  }

  private boolean validFields() {
    if (getFrom() == null || getFrom().isEmpty())
      return false;
    if (getTo() == null || getTo().isEmpty())
      return false;
    // date is set automatically
    return true;
  }

  /**
   * Basic Informations displayed for the Trip.
   *
   * @author Christian Tassler
   *
   */

  public class RouteInfo {
    public static final int BOOKED_AND_ACTIVE = 3;
    public static final int BOOKED_BUT_UNACTIVE = 2;
    public static final int NOT_BOOKED_FULL = 1;
    public static final int NOT_BOOKED = 0;
    private MapModel mapData;
    private String mapPosition;
    private Integer waypoindId = null;

    private Integer selectedCity = null;

    public Integer getSelectedCity() {
      return selectedCity;
    }

    public void setSelectedCity(Integer selectedCity) {
      this.selectedCity = selectedCity;
    }

    public List<SelectItem> getStopOvers() {

      List<SelectItem> stopItems = new ArrayList<SelectItem>();
      List<Waypoint> stopovers = getTripService().getWaypointsForTrip(
          trip);
      for (Waypoint p : stopovers)
        stopItems.add(new SelectItem(p.getId(), p.getFromLocation()
            .getCity()));

      return stopItems;
    }

    public String getMapPosition() {
      LatLng position = getMapData().getMarkers().get(0).getLatlng();
      return (position.getLat() + 0.025) + ","
          + (position.getLng() - 0.05);

    }

    public void setMapPosition(String mapPosition) {
      this.mapPosition = mapPosition;
    }

    public void setMapData(MapModel mapData) {
      this.mapData = mapData;
    }

    public MapModel getMapData() {
      if (mapData == null)
        mapData = tripService.getMapModelFromTrip(trip);
      return mapData;
    }

    public RouteInfo(Trip trip) {
      this.trip = trip;
      checkTripsWaypoints();
    }

    private void checkTripsWaypoints() {
      tripsWaypoints = new ArrayList<Waypoint>();
      tripsWaypoints.addAll(getTripService().getWaypointsForTrip(trip));
      tripsWaypoints.add(trip.getWaypoint());
    }

    /**
     * Compares all Waypoints of all Trips in all passed Routes with the
     * Users Waypoints and sets those Waypoints from the User to the Users
     * Waypoint stored in the Route. If the Route has no matching Waypoint,
     * a new one is used which means the Route has not been booked.
     *
     * @param routeInfos
     *            List of RouteInfos
     */

    protected void checkUserWaypoints(List<Waypoint> userWaypoints) {
      checkTripsWaypoints();
      boolean foundActive = false;
      for (Waypoint tripWp : this.tripsWaypoints) {
        for (Waypoint uw : userWaypoints) {
          if (tripWp.getId() == uw.getId()) {
            this.userWaypoint = uw;
            if (uw.isActive()) // if it is active stop looking
            {
              foundActive = true;
              break;
            }
          }
        }
        if (foundActive)
          break;
      }
    }

    /** The Trip the user will use */
    private Trip trip;
    /** The existing waypoints of this trip */
    private List<Waypoint> tripsWaypoints;
    /** The actual waypoints the user uses for this trip */
    private Waypoint userWaypoint;

    private Date arrivalDate = null;

    public Trip getTrip() {
      return trip;
    }

    public String getFrom() {
      return trip.getWaypoint().getFromLocation().getCity();
    }

    public String getTo() {
      return trip.getWaypoint().getToLocation().getCity();
    }

    public String getDepartureDate() {
      return jsfUtil.getSimpleDate().format(trip.getDeparture());
    }

    public String getDepartureTime() {
      return jsfUtil.getSimpleTime().format(trip.getDeparture());
    }

    private Date getArrivalDateTime() {
      if (arrivalDate == null) {
        arrivalDate = tripService.getArivalTime(trip);
      }
      return arrivalDate;
    }

    public String getArrivalDate() {

      return jsfUtil.getSimpleDate().format(getArrivalDateTime());
    }

    public String getArrivalTime() {
      return jsfUtil.getSimpleTime().format(getArrivalDateTime());
    }

    public boolean isBookable() {
      if (isLoggedIn()) {
        return getStatus() == NOT_BOOKED;
      }
      return false;
    }

    /**
     * If the Waypoint is persisted it is booked. But may or may not be
     * confirmed by the driver. {@link #getStatus()} returns a more detailed
     * code.
     *
     * @return if the Waypoint is booked
     */
    public boolean isBooked() {
      if (isLoggedIn()) {
        return this.getUserWaypoint().getId() >= 0;
      }
      return false;
    }

    /**
     *
     * @return if the Trip is deletable (-> logged in user is the owner of
     *         the trip)
     */
    public boolean isDeletableTrip() {
      if (isLoggedIn() && isOwner()) {
        return this.getUserWaypoint().getId() >= 0;
      }
      return false;
    }

    /**
     *
     * @return if the Lift is deletable (-> logged in user is a member of
     *         the trip)
     */
    public boolean isDeletableLift() {
      if (isLoggedIn() && isTripMember()) {
        return this.getUserWaypoint().getId() >= 0;
      }
      return false;
    }

    /**
     *
     * @return if the logged in User is the Owner of the Trip
     */
    public boolean isOwner() {
      if (trip.getUser().getId() == jsfUtil.getLoggedInUser().getId()) {
        return true;
      }
      return false;
    }

    /**
     *
     * @return if the logged in User is a Member of the Trip
     */
    public boolean isTripMember() {
      List<Waypoint> allUserWaypoints = getTripService()
          .getWaypointsForTrip(trip);
      for (Waypoint w : allUserWaypoints) {
        if (w.getUser().getId() == jsfUtil.getLoggedInUser().getId()) {
          this.waypoindId = w.getId();
          return true;
        }

      }
      return false;
    }

    public int getStatus() {
      if (isBooked()) {
        if (this.getUserWaypoint().isActive())
          return BOOKED_AND_ACTIVE;
        return BOOKED_BUT_UNACTIVE;
      }
      // tripsWaypoints also contains driver, therefore <1
      if (trip.getSeats() > tripsWaypoints.size() - 1) // has seats
        return NOT_BOOKED;
      return NOT_BOOKED_FULL;

    }

    /**
     * Returns the Username of the driver
     *
     * @return the Username of the driver
     */
    public String getDriverName() {
      return trip.getUser().getUsername();
    }

    /*
     * Following requires to be logged in
     */

    /**
     * Returns the First- and LastName of the driver
     *
     * @return the First- and LastName of the driver
     */
    public String getDriverFullName() {
      if (!isLoggedIn()) {
        requestLogin();
        return trip.getUser().getUsername();
      }

      return trip.getUser().getFirstName() + " "
          + trip.getUser().getLastName();
    }

    /**
     * Returns the number of free seats and total number of seats like "3/5"
     *
     * @return the number of free seats and total number of seats
     */
    public String getSeatsRatio() {
      // tripsWaypoints contains drivers waypoints, trip.seats not
      return (trip.getSeats() + 1 - tripsWaypoints.size()) + "/"
          + trip.getSeats();
    }

    // Stops info stores {stops_name, arriving time, available seats#}
    // of all stops(departure, middle stops, destination) in a list
    public List<StopInfo> getStopsInfo() {
      if (!isLoggedIn()) {
        requestLogin();
        return Collections.emptyList();
      }
      List<StopInfo> stopsInfo = new ArrayList<StopInfo>();
      List<Waypoint> userWaypoints = tripsWaypoints.subList(0, tripsWaypoints.size() -1 );
      for(Waypoint w: userWaypoints){
        StopInfo stopinfo = new StopInfo(w.getFromLocation(),w.getToLocation(),w.getUser().getUsername());
        stopsInfo.add(stopinfo);
      }
      return stopsInfo;
    }

    /**
     * Returns the Phonenumber of the Driver
     *
     * @return the Phonenumber of the Driver
     */
    public String getDriverPhone() {
      if (!isLoggedIn()) {
        requestLogin();
        return "";
      }
      return trip.getUser().getPhone();
    }

    /**
     * Adding an unactive Waypoint to the Trip and redirects to the
     * Confirmation page
     *
     * @param actionEvent
     *            ActionEvent of the clicked button
     */
    public void book(ActionEvent actionEvent) {
      if (isBooked()) { // prevent by disabling book button!
        logger.debug("Trip already booked");
        return;
      }
      if (!isLoggedIn()) {
        requestLogin();
        return;
      }

      setSelectedTrip(this);

      Waypoint wp = getUserWaypoint();
      getTripService().bookWaypointForTrip(wp, trip);

      // update this
      tripsWaypoints.add(trip.getWaypoint());

      // TODO notify Driver and User
      try {
        jsfUtil.redirect("./bookTripConfirmation.jsf");
      } catch (IOException e) {
        logger.error(
            "Error while redirecting to to booking conformation", e);
      }
    }

    /**
     * Deleting a trip & redirects to the tripDelelteConfirmation Page
     * Sending delete-notification-Emails to concerning users who booked the trip
     *
     * @param actionEvent
     *            ActionEvent of the clicked button
     */
    public void deleteTrip(ActionEvent actionEvent) {
      if (!isLoggedIn()) {
        requestLogin();
        return;
      }
     
      List<Waypoint> lw = getTripService().getWaypointsForTrip(trip);
      getTripService().removeTrip(String.valueOf(trip.getId()));
      clearCache();
      tripsWaypoints = Collections.emptyList();
      EmailUtil email = new EmailUtilImpl();
      for (Waypoint w : lw) {
        email.sendTripDeleteNotification(w.getUser().getEmail(), w.getUser().getUsername());
      }
     
      try {
        jsfUtil.redirect("./deleteTripConfirmation.jsf");
      } catch (IOException e) {
        logger.error(
            "Error while redirecting to delte conformation", e);
      }
    }

    /**
     * Deleting a waypoint & redirects to the liftDelelteConfirmation Page
     *
     * @param actionEvent
     *            ActionEvent of the clicked button
     */
    public void deleteLift(ActionEvent actionEvent) {
      if (!isLoggedIn()) {
        requestLogin();
        return;
      }

      if (this.waypoindId != null) {
        getTripService()
            .removeWaypoint(String.valueOf(this.waypoindId));
        this.waypoindId = null;
      }
      clearCache();
      tripsWaypoints = Collections.emptyList();
      // TODO notify Driver and User
      try {
        jsfUtil.redirect("./deleteWaypointConfirmation.jsf");
      } catch (IOException e) {
        logger.error(
            "Error while redirecting to delete conformation", e);
      }
    }

    /**
     * Returns the Waypoint for the user. This WayPoint initially is set
     * unactive and the locations are copies of the trips endpoints.
     *
     * @return the Waypoint of the user
     */
    public Waypoint getUserWaypoint() {
      if (!isLoggedIn())
        return null;
      if (userWaypoint == null) {
        userWaypoint = new Waypoint(new Location(trip.getWaypoint()
            .getFromLocation()), new Location(trip.getWaypoint()
            .getToLocation()), getLoggedInUser(), "", false);
      }
      return userWaypoint;
    }
   
    public boolean getHasUserWaypoints(){
      if(tripsWaypoints.size() > 1){
        return true;
      }
      else{
        return false;
      }
    }

  }

  /**
   * Like RouteInfo is for a Trip, StopInfo is for the Waypoints on the Trip.
   *
   * @author Christian Tassler
   *
   */
  public class StopInfo {
    // TODO in next iteration
   
    private Location fromLocation;
    private Location toLocation;
    private String user;
   
    public StopInfo(Location from, Location to, String user){
      setFromLocation(from);
      setToLocation(to);
      setUser(user);
    }
   
    public String getFromLocation() {
      return fromLocation.getCity();
    }
    public void setFromLocation(Location fromLocation) {
      this.fromLocation = fromLocation;
    }
    public String getToLocation() {
      return toLocation.getCity();
    }
    public void setToLocation(Location toLocation) {
      this.toLocation = toLocation;
    }
    public String getUser() {
      return user;
    }
    public void setUser(String user) {
      this.user = user;
    }
  }

  /**
   * Is called when there is no user logged in and it is be required that he
   * is.
   */
  private void requestLogin() {
    // TODO in next iteration
    logger.info("Functionality hasn't been implemented yet.");
  }

  /*
   * Buttons and Actions
   */
  /**
   * Activated when Search button is clicked. Redirects to the trips-page
   * using a generated url.
   */
  public void searchButtonClicked(ActionEvent actionEvent) {
    try {
      jsfUtil.redirect(getAllInSearchUrl());
    } catch (Exception e) {
      logger.error("Error while redirecting to search result", e);
    }
  }

  public void printButtonClicked() {
    PDFUtil pdf = new PDFUtil(getMatches(), new String(jsfUtil
        .getLoggedInUser().getFirstName()
        + " "
        + jsfUtil.getLoggedInUser().getLastName()));
    logger.info("PRINT");
    pdf.execute();

    logger.info("PRINT");
  }

  public void downloadPdf() {
    PDFUtil pdf = new PDFUtil(getMatches(), new String(jsfUtil
        .getLoggedInUser().getFirstName()
        + " "
        + jsfUtil.getLoggedInUser().getLastName()));

    InputStream pdfFile = pdf.execute();

    setPdfFile(new DefaultStreamedContent(pdfFile,
        "application/pdf", "driveTogether.pdf"));
//    DefaultStreamedContent file = new DefaultStreamedContent(pdfFile,
//        "application/pdf", "driveTogether.pdf");
   
//    return getPdfFile();

  }

  public void setPdfFile(DefaultStreamedContent pdfFile) {
    this.pdfFile = pdfFile;
  }

  public DefaultStreamedContent getPdfFile() {
    this.downloadPdf();
    return pdfFile;
  }

  public void setVisiblePDFButton(boolean visiblePDFButton) {
    this.visiblePDFButton = visiblePDFButton;
  }

  public boolean isVisiblePDFButton() {
    return visiblePDFButton;
  }

  @Override
  public void userLoggedIn(User user) {
    loggedInUser = user;
    checkRoutesUserWaypoints(getMatches());
  }

  @Override
  public void userLoggedOut() {
    loggedInUser = null;
  }
}
TOP

Related Classes of at.fhj.itm.beans.SearchTrip$RouteInfo

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.