/*******************************************************************************
 * 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;

/**** COMMON IMPORTS BEGIN ****/

import java.util.Hashtable;
import java.util.Set;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.n2bb.action.N2bbAction;
import com.n2bb.security.SecurityManager;
import com.n2bb.util.ActionConstants;
import com.n2bb.util.N2bbException;
import com.tandbergtv.workflow.auth.ACLEntry;
import com.tandbergtv.workflow.auth.AuthorizationManager;
import com.tandbergtv.workflow.auth.IAuthorizationManager;
import com.tandbergtv.workflow.auth.Role;
import com.tandbergtv.workflow.resourcemanager.ResourceManagement;
import com.tandbergtv.workflow.resourcemanager.ResourceManager;
import com.tandbergtv.workflow.web.common.StaticCodes;

public final class UserAction extends N2bbAction {
	
    private UserManager getUserManager() {
        return UserManager.getInstance();
    }

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        // defaultAction
        String defaultAction = ActionConstants.add;

        /******************** COMMON BEGIN *********************/
        HttpSession session = request.getSession();

        
        
        String action = request.getParameter("actionType");
        if (request.getAttribute("actionType") != null){
        	action = (String)request.getAttribute("actionType");
        }
        if (action == null || action.equals(""))
            action = defaultAction;
        n2bbLog.debug("action... " + action);

        ActionErrors errors = new ActionErrors();
        ActionForward fwd = new ActionForward("home");
        /******************** COMMON END ***********************/

        try {
            UserForm uf = (UserForm) form;

            // add user
            if (action.equals(ActionConstants.add)) {
                if (addUser(errors, session))
                    fwd = mapping.findForward("success");
                else
                    fwd = mapping.findForward("failure");
                // save user
            }
            else if (action.equals(ActionConstants.save)) {
                if (saveUser(errors, uf)) {
                	request.setAttribute(ActionConstants.save,ActionConstants.save);
                	fwd = mapping.findForward("success");
                	n2bbLog.debug("The path--->"+fwd);
                }
                else
                    fwd = mapping.findForward("failure");
                // edit user
            }
            else if (action.equals(ActionConstants.edit)) {
                if (editUser(errors, session, request)){
            		// For displaying Modify tab item in the menu.
            		request.setAttribute(StaticCodes.MODIFY_TAB_ITEM,
            				StaticCodes.MODIFY_TAB_ITEM);
                    fwd = mapping.findForward("success");
                }
                else
                    fwd = mapping.findForward("failure");
                // update user
            }
            else if (action.equals(ActionConstants.update)) {
                if (updateUser(errors, uf)) {
                	request.setAttribute(ActionConstants.update,ActionConstants.update);
                    fwd = mapping.findForward("success");
                }
                else{
        			fwd = mapping.findForward("failure");
                }
            }
        }
        catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other"));
            n2bbLog.error("exception - message... " + e.getMessage(), e);
        }

        if (!errors.isEmpty()) {
            saveErrors(request, errors);
        }

        return fwd;
    }

    /***************************************
     *
     ***************************************/
    private boolean addUser(ActionErrors errors, HttpSession session) {
        n2bbLog.debug("enter");

        try {
            Hashtable userHash = (Hashtable) session.getAttribute("userHash");
            if (userHash == null)
                userHash = new Hashtable();

            Vector n2RoleVector = new Vector();

            try {
                n2RoleVector = SecurityManager.getInstance().getRoleNames();
            }
            catch (N2bbException e) {
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.n2Roles"));
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
                n2bbLog.error("failed to get role names exception - message... " + e.getMessage(), e);
            }

            userHash.put("n2RoleVector", n2RoleVector);
            session.setAttribute("userHash", userHash);
            return true;
        }
        catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.add"));
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other"));
            n2bbLog.error("exception - message... " + e.getMessage(), e);
            return false;
        }
    }

    /************************
     *
     ************************/
    private boolean saveUser(ActionErrors errors, UserForm form) {
        n2bbLog.debug("enter");

        try {
            try {
                UserBean bean = convertFormToBean(form);
                getUserManager().saveUser(bean);
            }
            catch (N2bbException e) {
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.save"));
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
                n2bbLog.error("failed to save - message... " + e.getMessage(), e);
                return false;
            }

            return true;
        }
        catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.save"));
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other"));
            n2bbLog.error("exception - message... " + e.getMessage(), e);
            return false;
        }
    }

    /************************
     *
     ************************/
    private boolean editUser(ActionErrors errors, HttpSession session, HttpServletRequest request) {
        n2bbLog.debug("enter");

        try {
            Hashtable userHash = (Hashtable) session.getAttribute("userHash");
            if (userHash == null)
                userHash = new Hashtable();

            Vector n2RoleVector = new Vector();

            try {
                n2RoleVector = SecurityManager.getInstance().getRoleNames();
            }
            catch (N2bbException e) {
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.n2Roles"));
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
                n2bbLog.error("failed to get role names exception - message... " + e.getMessage(), e);
            }

            userHash.put("n2RoleVector", n2RoleVector);
            session.setAttribute("userHash", userHash);

            // get user
            try {
                String userName = request.getParameter("userName");
                UserBean bean = getUserManager().getUser(userName);
                UserForm form = convertBeanToForm(bean);
                form.setActionType(ActionConstants.edit);
                request.setAttribute("userForm", form);

            }
            catch (N2bbException e) {
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.edit"));
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
                n2bbLog.error("failed to get user exception - message... " + e.getMessage(), e);
                return false;
            }

            return true;
        }
        catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.edit"));
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other"));
            n2bbLog.error("exception - message... " + e.getMessage(), e);
            return false;
        }
    }

    /************************
     *
     ************************/
    private boolean updateUser(ActionErrors errors, UserForm form) {
        n2bbLog.debug("enter");

        try {

            UserBean bean = convertFormToBean(form);
          	ResourceManagement resourceManager = ResourceManager.getInstance();
            try {
            	
             	IAuthorizationManager authorizationManager = AuthorizationManager.getInstance();
            	            	
            	boolean isResourceExists = false;
            	if (resourceManager.getResourceByUser(form.getUserName()) != null) {
            		isResourceExists = true;
  				}
          		
          		if (isResourceExists == true){
	               	Role role = authorizationManager.getRole(form.getRoleName());
	               	Set<ACLEntry> setACLEntries = role.getACL();
	            	long performTaskId = 0; 
	            	
	            	// Getting the Perform Task Permission id 
	            	for (ACLEntry entry : setACLEntries){
	            		if(entry.getPermission().getName().equalsIgnoreCase(StaticCodes.PERMISSION_NAME_PERFORM_TASK)){
	            			performTaskId=entry.getPermission().getId();
	            			break;
	            		}
	            	}
	            	// throw exception if new role does not have Perform Task permission
	            	if (performTaskId == 0) {
	            		throw new N2bbException("error.userAction.userRoleChangeNotAllowed");
	            	}
	            	
          		}
                getUserManager().updateUser(bean, form.getChangePassword());
            }
            catch (N2bbException e) {
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.update"));
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
                n2bbLog.error("failed to update - message... " + e.getMessage(), e);
                return false;
            }

            return true;
        }
        catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.userAction.update"));
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other"));
            n2bbLog.error("exception - message... " + e.getMessage(), e);
            return false;
        }
    }

    /************************
     *
     ************************/
    private UserBean convertFormToBean(UserForm form) {
        UserBean bean = new UserBean();
        bean.setUserName(form.getUserName());
        bean.setPassword(form.getPassword());
        bean.setFirstName(form.getFirstName());
        bean.setLastName(form.getLastName());
        bean.setRoleName(form.getRoleName());
        bean.setStatus(form.getStatus());
        bean.setEmail(form.getEmail());
        bean.setPhone(form.getPhoneArea() + form.getPhoneFirst() + form.getPhoneLast());
        bean.setExtn(form.getExtn());
        bean.setEmployeeId(form.getEmployeeId());
        bean.setDepartment(form.getDepartment());
        bean.setLocation(form.getLocation());
        return bean;
    }

    /************************
     *
     ************************/
    private UserForm convertBeanToForm(UserBean bean) {
        UserForm form = new UserForm();
        form.setUserName(bean.getUserName());
        form.setPassword(bean.getPassword());
        form.setConfirmPassword(bean.getPassword());
        form.setFirstName(bean.getFirstName());
        form.setLastName(bean.getLastName());
        form.setRoleName(bean.getRoleName());
        form.setStatus(bean.getStatus());
        form.setEmail(bean.getEmail());

        String phone = bean.getPhone();
        if (phone.length() >= 3)
            form.setPhoneArea(phone.substring(0, 3));
        if (phone.length() >= 6)
            form.setPhoneFirst(phone.substring(3, 6));
        if (phone.length() >= 10)
            form.setPhoneLast(phone.substring(6, 10));
        form.setExtn(bean.getExtn());
        form.setEmployeeId(bean.getEmployeeId());
        form.setDepartment(bean.getDepartment());
        form.setLocation(bean.getLocation());
        
        return form;
    }

}

