/**
   * Delete past race
   *
   * @return
   */
  public static Result delete(Long raceId) {

    // Delete race
    PastRace pastRace = PastRace.find.byId(Long.valueOf(raceId));
    if (pastRace == null || !pastRace.user.equals(getConnectedUser())) {
      Logger.error("Past race save forbidden");
      return forbidden();
    } else {
      pastRace.delete();
    }

    // Redirect to user homepage
    return redirect(
        controllers.user.routes.UserController.index(Application.getConnectedUser().username));
  }
  /**
   * Save past race
   *
   * @return
   */
  public static Result save() {
    Form<PastRaceForm> form = form(PastRaceForm.class).bindFromRequest();
    // Is this an update or a creation?
    PastRace pastRace = null;
    boolean isnew = false;
    String raceId = form.field("id").value();
    if (!StringUtils.isEmpty(raceId)) {
      try {
        pastRace = PastRace.find.byId(Long.valueOf(raceId));
      } catch (NumberFormatException n) {
      }
      if (pastRace == null || !pastRace.user.equals(getConnectedUser())) {
        Logger.error("Past race save forbidden");
        return forbidden();
      }
    } else {
      isnew = true;
      pastRace = new PastRace();
      pastRace.dateCreation = new Date();
    }

    // Check date format
    Date date = null;
    if (form.error("date") == null) {
      DateFormat df = new SimpleDateFormat(Messages.get("general.dateformat"));
      try {
        date = df.parse(form.field("date").value());
      } catch (ParseException p) {
        form.reject("date", "general.error.dateformat");
      }
    }

    // Check time
    String hours = form.field("hours").value();
    String minutes = form.field("minutes").value();
    String seconds = form.field("seconds").value();
    if (StringUtils.isEmpty(hours)
        || StringUtils.isEmpty(minutes)
        || StringUtils.isEmpty(seconds)) {
      form.reject("time", "general.error.multiple");
    }

    int timeInSeconds = 0;
    try {
      timeInSeconds += Integer.parseInt(hours) * 3600;
      timeInSeconds += Integer.parseInt(minutes) * 60;
      timeInSeconds += Integer.parseInt(seconds);
    } catch (NumberFormatException n) {
      form.reject("time", "pastrace.error.time");
    }

    if (form.hasErrors()) {
      return badRequest(views.html.user.pastRace.render(form, isnew));
    } else {
      // Save past race
      pastRace.name = form.field("name").value();
      pastRace.date = date;
      pastRace.user = Application.getConnectedUser();
      pastRace.distance = form.field("distance").value();
      pastRace.time = timeInSeconds;
      Ebean.save(pastRace);

      // Redirect to user homepage
      return redirect(
          controllers.user.routes.UserController.index(Application.getConnectedUser().username));
    }
  }