/* (non-Javadoc)
   * @see org.wso2.carbon.identity.application.authentication.framework.AbstractApplicationAuthenticator#initiateAuthenticationRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)
   */
  @Override
  protected void initiateAuthenticationRequest(
      HttpServletRequest request, HttpServletResponse response, AuthenticationContext context)
      throws AuthenticationFailedException {

    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();

    String queryParams =
        FrameworkUtils.getQueryStringWithFrameworkContextId(
            context.getQueryParams(),
            context.getCallerSessionKey(),
            context.getContextIdentifier());

    try {

      String retryParam = "";

      if (context.isRetrying()) {
        retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
      } else {
        // Insert entry to DB only if this is not a retry
        DBUtils.insertUserResponse(
            context.getContextIdentifier(), String.valueOf(MSSAuthenticator.UserResponse.PENDING));
      }

      // MSISDN will be saved in the context in the MSISDNAuthenticator
      String msisdn = (String) context.getProperty("msisdn");
      MSSRequest mssRequest = new MSSRequest();
      mssRequest.setMsisdnNo("+" + msisdn);
      mssRequest.setSendString(
          DataHolder.getInstance().getMobileConnectConfig().getMSS().getMssText());

      String contextIdentifier = context.getContextIdentifier();
      MSSRestClient mssRestClient = new MSSRestClient(contextIdentifier, mssRequest);
      mssRestClient.start();

      response.sendRedirect(
          response.encodeRedirectURL(loginPage + ("?" + queryParams))
              + "&authenticators="
              + getName()
              + ":"
              + "LOCAL"
              + retryParam);

    } catch (IOException e) {
      throw new AuthenticationFailedException(e.getMessage(), e);
    } catch (AuthenticatorException e) {
      throw new AuthenticationFailedException(e.getMessage(), e);
    }
  }