package form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
/**
 * This ActionForm is used by the basketball application to validate
 * that the user has entered a userName and a password. If one or
 * both of the fields are empty when validate is called by the
 * ActionServlet, error messages are created.
 */
public class LoginForm extends ActionForm {
  // The user's private id number
  private String password;
  // The user's access number
  private String userName;

  public LoginForm() {
    super();
    resetFields();
  }
  /**
   * Called by the framework to validate the user has entered the
   * userName and password fields.
   */
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest req ){
    ActionErrors errors = new ActionErrors();

    // Get access to the message resources for this application
    // There's not an easy way to access the resources from an ActionForm
    MessageResources resources =
      (MessageResources)req.getAttribute( Action.MESSAGES_KEY );

    // Check and see if the user name is missing
    if(userName == null || userName.length() == 0) {
      String userNameLabel = resources.getMessage( "label.username" );
      ActionError newError =
        new ActionError("global.error.login.requiredfield", userNameLabel );
      errors.add(ActionErrors.GLOBAL_ERROR, newError);
    }

    // Check and see if the password is missing
    if(password == null || password.length() == 0) {
      String passwordLabel = resources.getMessage( "label.password" );
      ActionError newError =
        new ActionError("global.error.login.requiredfield", passwordLabel );
      errors.add(ActionErrors.GLOBAL_ERROR, newError);
    }
    // Return the ActionErrors, in any.
    return errors;
  }

  /**
   * Called by the framework to reset the fields back to their default values.
   */
  public void reset(ActionMapping mapping, HttpServletRequest request) {
    // Clear out the user name and password fields
    resetFields();
  }
  /**
   * Reset the fields back to their defaults.
   */
  protected void resetFields() {
    this.userName = "";
    this.password = "";
  }

  public void setUserName(String name) {
    this.userName = name;
  }

  public String getUserName() {
    return this.userName;
  }

  public String getPassword() {
    return this.password;
  }
  public void setPassword(String pass) {
    this.password = pass;
  }
}