/********************************************************************
 * Copyright © 2004 EDS. All rights reserved
 ********************************************************************/
package gov.vha.edb.rules.web.builder;

import gov.vha.edb.rules.repository.EDBRepository;
import java.util.*;

/**
 * Role : form parameter validation
 *
 * @author
 */
public class ValidationBean {

  /**
   * Validation error message table
   */
  protected Hashtable errors;

  /**
   * Notification of error at validation time
   */
  protected boolean hasErrors;

  /**
   * Form entries
   */
  private String userId;
  private String password;

  /**
   * Validate the form parameters
   *
   * @return  true if all form parameters are valid, false otherwise
   */
  public boolean validate() {
    boolean allOk = true;
    flushErrors();

    if ((userId == null) || (userId.equals(""))) {
      addErrorMsg("userId", "Invalid User ID");
      userId = "";
      allOk = false;
    }

    // Check password validity 
    if ((password == null) || (password.equals("")))
    {
        addErrorMsg("password", "Invalid Password");
        password = "";
        allOk = false;
    }
    
    if (allOk && !EDBRepository.validate(userId, password)){
    	addErrorMsg("userId", "Invalid UserId/Password combination!");
    	allOk = false;
    }

    hasErrors(!(allOk));

    return allOk;
  }

  /**
   * Constructor
   */
  public ValidationBean() {
    hasErrors = false;
    errors = new Hashtable();

    userId = "";
    password = "";
  }

  /**
   * Form entry getter
   */
  public String getUserId() {
    return userId;
  }

  public String getPassword() {
    return password;
  }

  /**
   * Form entry setter
   */
  public void setUserId(String value) {
    userId = value;
  }

  public void setPassword(String value) {
    password = value;
  }

  /**
   * Retrieve a validation error message
   *
   * @param   s: the error message key
   * @return  the error message text if the parameter key entry exists
   */
  public String getErrorMsg(String s) {
    String errorMsg = (String) errors.get(s.trim());
    return (errorMsg == null) ? "" : errorMsg;
  }

  /**
   * Add an error message
   *
   * @param   key: error message key
   * @param   msg: error message text
   */
  public void addErrorMsg(String key, String msg) {
    hasErrors = true;
    errors.put(key, msg);
  }

  /**
   * Retrieve existence of validation error(s)
   *
   * @return  true if there was any error, false otherwise
   */
  public boolean hasErrors() {
    return hasErrors;
  }

  /**
   * Set existence of validation error(s)
   *
   */
  public void hasErrors(boolean value) {
    hasErrors = value;
  }

  /**
   * Reset error related entries
   */
  public void flushErrors() {
    hasErrors = false;
    errors = new Hashtable();
  }


}