/*******************************************************************************
 * Copyright (c), 2001, 2002 N2 Broadband, Inc.  All Rights Reserved.
 *
 * This module contains unpublished, confidential, proprietary
 * material.  The use and dissemination of this material are
 * governed by a license.  The above copyright notice does not
 * evidence any actual or intended publication of this material.
 *
 * Author:  Drake H. Henderson
 * Created:  11-12-01
 *
 ******************************************************************************/

package com.n2bb.user;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 com.n2bb.util.ActionConstants;
import com.n2bb.security.N2bbRoleConsts;
import com.n2bb.util.N2bbException;
import com.n2bb.util.N2bbEmail;
import com.n2bb.util.N2bbUtility;
import com.n2bb.util.N2bbSettings;

/**
 * Struts form for editing properties of user of system.
 *
 * @author dhenderson
 * @author kmatsuoka
 * @version $Id: UserForm.java,v 1.3 2006/09/01 18:14:02 rao Exp $
 */
public final class UserForm extends ActionForm {

  private Log n2bbLog = LogFactory.getLog(N2bbSettings.N2BB_LOG);

  /**
   * The maintenance action we are performing (Add or Edit).
   */
  private String actionType = ActionConstants.add;
  private String userName = null;
  private boolean changePassword = false;
  private String password = null;
  private String confirmPassword = null;
  private String firstName = null;
  private String lastName = null;
  private String roleName = null;
  private String status = null;
  private String email = null;
  private String phoneArea = null;
  private String phoneFirst = null;
  private String phoneLast = null;
  private String extn = null;
  private String employeeId = null;
  private String department = null;
  private String location = null;

  /**
   * Return the maintenance action.
   */
  public String getActionType() {
    return (this.actionType);
  }

  /**
   * Set the maintenance action.
   *
   * @param action The new maintenance action.
   */
  public void setActionType(String actionType) {
    this.actionType = actionType;
  }

  /**
   * Reset all properties to their default values.
   *
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
   */
  public void reset(ActionMapping mapping, HttpServletRequest request) {
    userName = null;
    changePassword = false;
    password = null;
    confirmPassword = null;
    firstName = null;
    lastName = null;
    roleName = null;
    email = null;
    phoneArea = null;
    phoneFirst = null;
    phoneLast = null;
    extn = null;
    status = null;
    employeeId = null;
    department = null;
    location = null;
  }

  /**
   * Validate the properties that have been set from this HTTP request,
   * and return an <code>ActionErrors</code> object that encapsulates any
   * validation errors that have been found.  If no errors are found, return
   * <code>null</code> or an <code>ActionErrors</code> object with no
   * recorded error messages.
   *
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
   */
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

    ActionErrors errors = new ActionErrors();
    try {

      // first name
      if (getFirstName().equals(""))
        errors.add("firstName", new ActionError("error.user.firstNameRequired"));

      if (getFirstName().length() > 60)
        errors.add("firstName", new ActionError("error.user.firstNameTooLong"));

      // last name
      if (getLastName().equals(""))
        errors.add("lastName", new ActionError("error.user.lastNameRequired"));

      if (getLastName().length() > 60)
        errors.add("lastName", new ActionError("error.user.lastNameTooLong"));

      // user name
      if (getUserName().equals(""))
        errors.add("userName", new ActionError("error.user.userNameRequired"));

      if (!N2bbUtility.isLoginName(getUserName()))
        errors.add("userName", new ActionError("error.user.userNameInvalid"));

      if (getUserName().length() < 3 || getUserName().length() > 96)
        errors.add("userName", new ActionError("error.user.userNameLength"));

      // user name
      if (getRoleName().equals(""))
        errors.add("roleName", new ActionError("error.user.roleNameRequired"));

      // should always be true when creating a new user
      // should only be true on updating a user when the checkbox is selected
      if (getChangePassword()) {
        // password
        if (getPassword().equals(""))
          errors.add("password", new ActionError("error.user.passwordRequired"));

        if (getPassword().length() < 6 || getPassword().length() > 16)
          errors.add("password", new ActionError("error.user.passwordLength"));

        if (getPassword().equals(getUserName()))
          errors.add("password", new ActionError("error.user.passwordUserName"));

        // confirm password
        if (getConfirmPassword().equals(""))
          errors.add("confirmPassword", new ActionError("error.user.confirmPasswordRequired"));

        if (!getPassword().equals(getConfirmPassword()))
          errors.add("confirmPassword", new ActionError("error.user.confirmPasswordPassword"));
      }

      // email
      if (getEmail().equals(""))
        errors.add("email", new ActionError("error.user.emailRequired"));
      else {
        n2bbLog.debug("email... '" + getEmail() + "'");

        try {
          N2bbEmail email = new N2bbEmail(getEmail());
        } catch (N2bbException e) {
          n2bbLog.debug("email n2bb exception - message... " + e.getMessage());
          errors.add("email", new ActionError(e.getErrorCode()));
        }
        catch (Exception e) {
          n2bbLog.error("email exception - message... " + e.getMessage(), e);
          errors.add("email", new ActionError("error.email.validationFailed"));
        }
      }

      // employeed id
      
      if (getEmployeeId().equals(""))
          errors.add("employeeId", new ActionError("error.user.employeeIdRequired"));

      if (getEmployeeId().length() > 50)
          errors.add("employeeId", new ActionError("error.user.employeeIdTooLong"));
		
		//Department
      if (getDepartment().equals(""))
		    errors.add("department", new ActionError("error.user.departmentRequired"));
		
      if (getDepartment().length() > 50)
		    errors.add("department", new ActionError("error.user.departmentTooLong"));
        
		  //Location
      if (getLocation().equals(""))
    	  errors.add("location", new ActionError("error.user.locationRequired"));
      
      if (getLocation().length() > 50)
    	  errors.add("location", new ActionError("error.user.locationTooLong"));
      
      
      // phone
      String phone = (getPhoneArea() + getPhoneFirst() + getPhoneLast()).trim();
      if (!phone.equals("")) {
        if (!N2bbUtility.isDigits(phone))
          errors.add("phone", new ActionError("error.user.phoneInvalid"));

        if (phone.length() < 10)
          errors.add("phone", new ActionError("error.user.phoneTooShort"));
      }

    }
    catch (Exception e) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other.validation"));
      n2bbLog.error("exception - message... " + e.getMessage(), e);
    }

    return errors;
  }

    /**
     * Checks if this user is the special N2BB Admin User.
     *
     * @return true if this user is the special N2BB Admin User
     */
    public boolean isAdminUser() {
        return userName != null &&
                userName.equalsIgnoreCase(N2bbSettings.ADMIN_USER);
    }

    /**
     * Checks if this form is being used to edit a user, based on action
     * seen when loading page.
     *
     * @return true if this form is being used to edit a user
     */
    public boolean isEdit() {
        return actionType != null &&
                (actionType.equals(ActionConstants.edit) ||
                 actionType.equals(ActionConstants.update));
    }

    /**
     * Gets action to use when submitting form.
     *
     * @return action to use when submitting form
     */
    public String getSubmitAction() {
        return isEdit() ? ActionConstants.update : ActionConstants.save;
    }

    /**
     * Gets role necessary to save form.
     *
     * @return role necessary to save form
     */
    public String getSaveRole() {
        return isEdit() ? N2bbRoleConsts.modifyRoles : N2bbRoleConsts.createRoles;
    }

  public String getUserName() {
    return userName == null ? "" : userName;
  }

  public boolean getChangePassword() {
    return changePassword;
  }

  public String getPassword() {
    return password == null ? "" : password;
  }

  public String getConfirmPassword() {
    return confirmPassword == null ? "" : confirmPassword;
  }

  public String getFirstName() {
    return firstName == null ? "" : firstName.trim();
  }

  public String getLastName() {
    return lastName == null ? "" : lastName.trim();
  }

  public String getRoleName() {
    return roleName == null ? "" : roleName.trim();
  }

  public String getStatus() {
    return status == null ? "" : status.trim();
  }

  public String getEmail() {
    return email == null ? "" : email.trim();
  }

  public String getPhoneArea() {
    return phoneArea == null ? "" : phoneArea.trim();
  }

  public String getPhoneFirst() {
    return phoneFirst == null ? "" : phoneFirst.trim();
  }

  public String getPhoneLast() {
    return phoneLast == null ? "" : phoneLast.trim();
  }

  public void setUserName(String userName) {
    this.userName = userName;
  }

  public void setChangePassword(boolean changePassword) {
    this.changePassword = changePassword;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName.trim();
  }

  public void setLastName(String lastName) {
    this.lastName = lastName.trim();
  }

  public void setRoleName(String roleName) {
    this.roleName = roleName;
  }

  public void setStatus(String status) {
    this.status = status;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public void setPhoneArea(String phoneArea) {
    this.phoneArea = phoneArea;
  }

  public void setPhoneFirst(String phoneFirst) {
    this.phoneFirst = phoneFirst;
  }

  public void setPhoneLast(String phoneLast) {
    this.phoneLast = phoneLast;
  }

public String getDepartment() {
	return department == null ? "" :department.trim();
}

public void setDepartment(String department) {
	this.department = department;
}

public String getEmployeeId() {
	return employeeId == null ? "" : employeeId.trim();
}

public void setEmployeeId(String employeeId) {
	this.employeeId = employeeId;
}

public String getExtn() {
	return extn == null ? "" : extn.trim();
}

public void setExtn(String extn) {
	this.extn = extn;
}

public String getLocation() {
	return location == null ? "" : location.trim();
}

public void setLocation(String location) {
	this.location = location;
}

}

/*
public boolean validatePasswordChange(String oldPassword, String newPassword, String confirmPassword) {
    try {
        // old password
        if (oldPassword.equals("")) {
            if (errAdded) error += "$n";
            else focus = "oldPassword";
            error += "Old password is required.";
            errAdded = true;
        }
        // compare old password with current password
        if (!oldPassword.equalsIgnoreCase(getPassword())) {
            if (errAdded) error += "$n";
            else focus = "oldPassword";
            error += "Incorrect old password.";
            errAdded = true;
        }

        // new password
        if (newPassword.equals("")) {
            if (errAdded) error += "$n";
            else focus = "newPassword";
            error += "New password is required.";
            errAdded = true;
        }
        if (newPassword.length() < 6 || oldPassword.length() > 16) {
            if (errAdded) error += "$n";
            else focus = "newPassword";
            error += "New password must be between 6 and 16 characters.";
            errAdded = true;
        }

        if (newPassword.equals(oldPassword)) {
            if (errAdded) error += "$n";
            else focus = "newPassword";
            error += "Old password and new password cannot not be the same.";
            errAdded = true;
        }

        // confirm password
        if (confirmPassword.equals("")) {
            if (errAdded) error += "$n";
            else focus = "confirmPassword";
            error += "Confirm password is required.";
            errAdded = true;
        }
        if (!newPassword.equals(confirmPassword)) {
            if (errAdded) error += "$n";
            else focus = "confirmPassword";
            error += "Confirm password and new password must be the same.";
            errAdded = true;
        }
*/






