@Controller
public class RegisterController {

  FlxLogger logger = FlxLogger.getLogger(RegisterController.class);

  @Qualifier("authenticationManager")
  AuthenticationManager authenticationManager;

  @Autowired GuestService guestService;

  @RequestMapping("/register")
  public String register() {
    return "register";
  }

  @RequestMapping("/createAccountForm")
  public String createAccountForm() {
    return "createAccount";
  }

  @RequestMapping("/createAccount")
  public ModelAndView createAccount(
      @RequestParam("email") String email,
      @RequestParam("username") String username,
      @RequestParam("firstname") String firstname,
      @RequestParam("lastname") String lastname,
      @RequestParam("password1") String password,
      @RequestParam("password2") String password2,
      //		@RequestParam("recaptchaChallenge") String challenge,
      //		@RequestParam("recaptchaResponse") String uresponse,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    email = email.trim();
    password = password.trim();
    password2 = password2.trim();
    username = username.trim();
    firstname = firstname.trim();
    lastname = lastname.trim();

    List<String> required = new ArrayList<String>();
    List<String> errors = new ArrayList<String>();
    if (email == "") required.add("email");
    if (username == "") {
      required.add("username");
    } else if (guestService.getGuest(username) != null) {
      errors.add("usernameTaken");
    }
    if (password == "") required.add("password");
    if (password2 == "") required.add("password2");
    if (password.length() < 8) errors.add("passwordTooShort");
    if (!password.equals(password2)) errors.add("passwordsDontMatch");
    if (guestService.getGuestByEmail(email) != null) errors.add("userExists");

    //		String remoteAddr = request.getRemoteAddr();
    //        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    //        reCaptcha.setPrivateKey("6LeXl8QSAAAAADjPASFlMINNRVwtlpcvGugcr2RI");
    //
    //        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge,
    // uresponse);
    //
    //		if (!reCaptchaResponse.isValid())
    //		errors.add("wrongCaptcha");

    if (errors.size() == 0 && required.size() == 0) {
      logger.info("action=register success=true username="******" email=" + email);
      guestService.createGuest(username, firstname, lastname, password, email);
      request.setAttribute("username", username);
      request.setAttribute("password", password);
      return new ModelAndView("accountCreationComplete");
    } else {
      logger.info("action=register errors=true");
      ModelAndView mav = new ModelAndView("createAccount");
      mav.addObject("email", email);
      mav.addObject("username", username);
      mav.addObject("firstname", firstname);
      mav.addObject("lastname", lastname);
      mav.addObject("errors", errors);
      mav.addObject("required", required);
      return mav;
    }
  }
}
/** Extracts information from the apicall and creates a facet */
@Component
public class BodymediaStepFacetExtractor extends AbstractFacetExtractor {

  // Logs various transactions
  FlxLogger logger = FlxLogger.getLogger(BodymediaStepFacetExtractor.class);

  @Qualifier("connectorUpdateServiceImpl")
  @Autowired
  ConnectorUpdateService connectorUpdateService;

  DateTimeFormatter form = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmssZ");
  DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");

  @Qualifier("metadataServiceImpl")
  @Autowired
  MetadataService metadataService;

  @Override
  public List<AbstractFacet> extractFacets(ApiData apiData, ObjectType objectType)
      throws Exception {

    logger.info(
        "guestId="
            + apiData.updateInfo.getGuestId()
            + " connector=bodymedia action=extractFacets objectType="
            + objectType.getName());

    ArrayList<AbstractFacet> facets;
    String name = objectType.getName();
    if (name.equals("steps")) {
      facets = extractStepFacets(apiData);
    } else // If the facet to be extracted wasn't a step facet
    {
      throw new RuntimeException("Step extractor called with illegal ObjectType");
    }
    return facets;
  }

  private ArrayList<AbstractFacet> extractStepFacets(final ApiData apiData) {
    ArrayList<AbstractFacet> facets = new ArrayList<AbstractFacet>();
    /* burnJson is a JSONArray that contains a seperate JSONArray and calorie counts for each day
     */
    JSONObject bodymediaResponse = JSONObject.fromObject(apiData.json);
    JSONArray daysArray = bodymediaResponse.getJSONArray("days");
    if (bodymediaResponse.has("lastSync")) {
      DateTime d =
          form.parseDateTime(bodymediaResponse.getJSONObject("lastSync").getString("dateTime"));

      // Get timezone map from UpdateInfo context
      TimezoneMap tzMap = (TimezoneMap) updateInfo.getContext("tzMap");

      // Insert lastSync into the updateInfo context so it's accessible to the updater
      updateInfo.setContext("lastSync", d);

      for (Object o : daysArray) {
        if (o instanceof JSONObject) {
          JSONObject day = (JSONObject) o;
          BodymediaStepsFacet steps = new BodymediaStepsFacet(apiData.updateInfo.apiKey.getId());
          super.extractCommonFacetData(steps, apiData);
          steps.totalSteps = day.getInt("totalSteps");
          steps.date = day.getString("date");
          steps.json = day.getString("hours");
          steps.lastSync = d.getMillis();

          DateTime date = formatter.parseDateTime(day.getString("date"));
          steps.date = dateFormatter.print(date.getMillis());
          if (tzMap != null) {
            // Create a LocalDate object which just captures the date without any
            // timezone assumptions
            LocalDate ld =
                new LocalDate(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth());
            // Use tzMap to convert date into a datetime with timezone information
            DateTime realDateStart = tzMap.getStartOfDate(ld);
            // Set the start and end times for the facet.  The start time is the leading midnight
            // of date according to BodyMedia's idea of what timezone you were in then.
            // Need to figure out what end should be...
            steps.start = realDateStart.getMillis();
            int minutesLength = 1440;
            steps.end = steps.start + DateTimeConstants.MILLIS_PER_MINUTE * minutesLength;
          } else {
            TimeZone timeZone =
                metadataService.getTimeZone(apiData.updateInfo.getGuestId(), date.getMillis());
            long fromMidnight = TimeUtils.fromMidnight(date.getMillis(), timeZone);
            long toMidnight = TimeUtils.toMidnight(date.getMillis(), timeZone);
            steps.start = fromMidnight;
            steps.end = toMidnight;
          }
          facets.add(steps);
        } else throw new JSONException("Days array is not a proper JSONObject");
      }
    }
    return facets;
  }
}