/*
 * $Id: UserListAction.java,v 1.30 2006/10/04 03:15:00 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: UserListAction.java,v $
 * Revision 1.30  2006/10/04 03:15:00  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.29  2006/05/18 22:50:53  marbobo
 * + Benutzerlöschen auf alte Methode umgestellt
 *
 * Revision 1.28  2006/04/29 18:36:08  marbobo
 * + Benutzerlöschen Überarbeitet
 *
 * Revision 1.27  2005/02/16 23:00:31  marbobo
 * + Suche auf Unicode-Zeichen erweitert
 *
 * Revision 1.26  2005/02/14 14:01:46  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.25  2004/11/10 15:02:50  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.24  2004/11/05 01:52:55  marbobo
 * + hasPublishedDocuments -> hasUserAnyDocuments()
 *
 * Revision 1.23  2004/09/16 13:10:54  marbobo
 * + Auf VKCRequestProcessor umgestellt
 *
 * Revision 1.22  2004/08/12 21:41:24  marbobo
 * + Actions auf Requestparameter umgestellt
 * + Bugfixes und Quellcode maintenance
 *
 * Revision 1.21  2004/07/20 08:06:03  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.administration.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import vkc.administration.form.UserListForm;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.misc.VKCLogManager;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;
import vkc.view.bean.UserInfo;

public class UserListAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/administration/userList.jsp");

	private ActionForward INFO_FORWARD = new ActionForward("/templates/${template.name}/common/InfoPage.jsp");

	private String infoString = "";

	public ActionForward execute(ActionMapping mapping, 
								 ActionForm f,
								 HttpServletRequest request, 
								 HttpServletResponse response)
	throws IOException, ServletException {
		try {
			UserListForm form = (UserListForm) f;
			VKCUser user = form.getUser();

			if (!user.hasAdminPrivileges() && !user.getManageOwnUsers()) {
				request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");

				return INFO_FORWARD;
			}

			infoString = "";

			if (request.getParameter("action.change.sortmode") != null) {
				return handleChangeSortMode(form, request);
			} else if (request.getParameter("action.change.listindex") != null) {
				form.setSelectedIds(new Integer[0]);

				return DEFAULT_FORWARD;
			} else if (request.getParameter("action.change.usersperpage") != null) {
				form.setSelectedIds(new Integer[0]);
				form.setListIndex(new Integer(0));

				return DEFAULT_FORWARD;
			} else if (request.getParameter("action.delete.users") != null) {
				return handleDeleteUsersAction(form, request);
			} else if (request.getParameter("action.disable.users") != null) {
				return handleDisableUsersAction(form, request);
			} else if (request.getParameter("action.enable.users") != null) {
				return handleEnableUsersAction(form, request);
			} else if (request.getParameter("action.unlock.users") != null) {
                return handleUnlockUsersAction(form, request);
			} else if (request.getParameter("action.search.redirect") != null) {
				form.setSearchQuery(VKCStringUtils.base64Decode(form.getSearchQuery()));
				
				if (request.getParameter("infoMessage") != null) {
					request.setAttribute(WebShare.MESSAGE_KEY, VKCStringUtils.base64Decode(request.getParameter("infoMessage")));
				}

				return handleInitializeAction(form, request);
			} else {
				return handleInitializeAction(form, request);
			}
		} catch (Throwable e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}

	private ActionForward handleDeleteUsersAction(UserListForm form, HttpServletRequest request) throws ServletException {
		try {
			VKCUser user = form.getUser();
			Locale locale = user.getLanguage().getLocale();
			MessageResources mRes = form.getResources();
			Integer[] selectedIds = form.getSelectedIds();
			String lockedUsers = null;
			String deletedUsers = null;
			HashMap userMap = new HashMap();
			UserInfo[] users = form.getUserInfos();
			int visibleUsersCount = form.getVisibleUserInfoSizes().intValue();
			int lockedUsersCount = 0;
			int deletedUsersCount = 0;

			for (int i = 0; i < users.length; i++) {
				userMap.put(users[i].getUserId(), users[i].getUsername());
			}

			for (int i = 0; i < selectedIds.length; i++) {
				if (selectedIds[i].intValue() == user.getUserId().intValue()) {
					infoString = infoString
							+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.loggedUser")
							+ "\\n";
				} else {
					if (VKCDocumentSerializer.hasUserAnyDocuments(selectedIds[i])) {
						VKCUser lockUser = VKCUserSerializer.retrieveUser(selectedIds[i]);
						lockUser.setAccountValid(false);
						lockUser.setLastChanged(new Timestamp(System.currentTimeMillis()));
						lockUser.setLastChangerId(user.getUserId());
						VKCUserSerializer.saveUser(lockUser);

						if (lockedUsers == null) {
							lockedUsers = lockUser.getUser();
						} else {
							lockedUsers += ", " + lockUser.getUser();
						}

						lockedUsersCount++;
					} else {
						VKCUserSerializer.deleteUser(selectedIds[i]);

						if (deletedUsers == null) {
							deletedUsers = (String) userMap.get(selectedIds[i]);
						} else {
							deletedUsers += ", " + (String) userMap.get(selectedIds[i]);
						}

						deletedUsersCount++;
					}
				}
			}

			if (selectedIds.length > 0) {
				if (selectedIds.length == 1) {
					if (lockedUsersCount == 1) {
						infoString = infoString
								+ lockedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.failed")
								+ " " + lockedUsers + "\\n";
					} else if (deletedUsersCount == 1) {
						infoString = infoString
								+ deletedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.done")
								+ " " + deletedUsers + "\\n";
					}
				} else {
					if (lockedUsersCount == 1) {
						infoString = infoString
								+ lockedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.failed")
								+ " " + lockedUsers + "\\n";
					} else if (lockedUsersCount > 1) {
						infoString = infoString
								+ lockedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUsers.failed")
								+ " " + lockedUsers + "\\n";
					}

					if (deletedUsersCount == 1) {
						infoString = infoString
								+ deletedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.done")
								+ " " + deletedUsers + "\\n";
					} else if (deletedUsersCount > 1) {
						infoString = infoString
								+ deletedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUsers.done")
								+ " " + deletedUsers + "\\n";
					}
				}
			}

			if (deletedUsersCount >= visibleUsersCount) {
				int listIndex = form.getListIndex().intValue();
				listIndex -= form.getUsersPerPage().intValue();

				if (listIndex <= 0) {
					form.setListIndex(new Integer(0));
				} else {
					form.setListIndex(new Integer(listIndex));
				}
			}

			if (deletedUsersCount > 0 || lockedUsersCount > 0) {
				form.setUserInfos(null);
			}

			request.setAttribute(WebShare.MESSAGE_KEY, infoString);

			return handleInitializeAction(form, request);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	protected ActionForward handleDeleteUsersNewAction(UserListForm form, HttpServletRequest request) throws ServletException {
		try {
			VKCUser user = form.getUser();
			Locale locale = user.getLanguage().getLocale();
			MessageResources mRes = form.getResources();
			Integer[] selectedIds = form.getSelectedIds();
			String deletedUsers = null;
			HashMap userMap = new HashMap();
			UserInfo[] users = form.getUserInfos();
			int visibleUsersCount = form.getVisibleUserInfoSizes().intValue();
			int deletedUsersCount = 0;
			HashSet lockedUserIds = new HashSet();
			HashSet deletedUserIds = new HashSet();
			String params = "";

			for (int i = 0; i < selectedIds.length; i++) {
				if (VKCDocumentSerializer.hasUserAnyDocuments(selectedIds[i])) {
					lockedUserIds.add(selectedIds[i]);
					params += "&lockedUserIds=" + selectedIds[i];
				} else {
					deletedUserIds.add(selectedIds[i]);
					params += "&deletedUserIds=" + selectedIds[i];
				}
			}

			if (!lockedUserIds.isEmpty()) {
				return new ActionForward(form.getDeleteUsersLink() + params, true);
			}
			
			for (int i = 0; i < users.length; i++) {
				userMap.put(users[i].getUserId(), users[i].getUsername());
			}

			if (deletedUserIds.contains(user.getUserId())) {
				infoString = infoString
						+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.loggedUser")
						+ "\\n";
				deletedUserIds.remove(user.getUserId());
			}
			
			for (Iterator iter = deletedUserIds.iterator(); iter.hasNext();) {
				Integer id = (Integer) iter.next();
				
				VKCUserSerializer.deleteUser(id);

				if (deletedUsers == null) {
					deletedUsers = (String) userMap.get(id);
				} else {
					deletedUsers += ", " + (String) userMap.get(id);
				}

				deletedUsersCount++;
			}
			
			if (selectedIds.length > 0) {
				if (selectedIds.length == 1) {
					if (deletedUsersCount == 1) {
						infoString = infoString
								+ deletedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.done")
								+ " " + deletedUsers + "\\n";
					}
				} else {
					if (deletedUsersCount == 1) {
						infoString = infoString
								+ deletedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.done")
								+ " " + deletedUsers + "\\n";
					} else if (deletedUsersCount > 1) {
						infoString = infoString
								+ deletedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.deleteUsers.done")
								+ " " + deletedUsers + "\\n";
					}
				}
			}

			if (deletedUsersCount >= visibleUsersCount) {
				int listIndex = form.getListIndex().intValue();
				listIndex -= form.getUsersPerPage().intValue();

				if (listIndex <= 0) {
					form.setListIndex(new Integer(0));
				} else {
					form.setListIndex(new Integer(listIndex));
				}
			}

			if (deletedUsersCount > 0) {
				form.setUserInfos(null);
			}

			request.setAttribute(WebShare.MESSAGE_KEY, infoString);

			return handleInitializeAction(form, request);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	private ActionForward handleDisableUsersAction(UserListForm form, HttpServletRequest request) throws ServletException {
		try {
			VKCUser user = form.getUser();
			Locale locale = user.getLanguage().getLocale();
			MessageResources mRes = form.getResources();
			Integer[] selectedIds = form.getSelectedIds();
			String lockedUsers = null;
			int lockedUsersCount = 0;

			for (int i = 0; i < selectedIds.length; i++) {
				if (selectedIds[i].intValue() == user.getUserId().intValue()) {
					infoString = infoString
							+ mRes.getMessage(locale, "vkc.administration.userList.lockUser.loggedUser")
							+ "\\n";
				} else {
					VKCUser lockUser = VKCUserSerializer.retrieveUser(selectedIds[i]);
					lockUser.setAccountValid(false);
					lockUser.setLastChanged(new Timestamp(System.currentTimeMillis()));
					lockUser.setLastChangerId(user.getUserId());
					VKCUserSerializer.saveUser(lockUser);

					if (lockedUsers == null) {
						lockedUsers = lockUser.getUser();
					} else {
						lockedUsers += ", " + lockUser.getUser();
					}

					lockedUsersCount++;
				}
			}

			if (selectedIds.length > 0) {
				if (selectedIds.length == 1) {
					if (lockedUsersCount == 1) {
						infoString = infoString
								+ lockedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.lockUser.done")
								+ " " + lockedUsers + "\\n";
					}
				} else {
					if (lockedUsersCount == 1) {
						infoString = infoString
								+ lockedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.lockUser.done")
								+ " " + lockedUsers + "\\n";
					} else {
						infoString = infoString
								+ lockedUsersCount
								+ " "
								+ mRes.getMessage(locale, "vkc.administration.userList.lockUsers.done")
								+ " " + lockedUsers + "\\n";
					}
				}
			}

			request.setAttribute(WebShare.MESSAGE_KEY, infoString);

			return handleInitializeAction(form, request);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	private ActionForward handleUnlockUsersAction(UserListForm form, HttpServletRequest request) throws ServletException {
		try {
			VKCUser user = form.getUser();
			Locale locale = user.getLanguage().getLocale();
			MessageResources mRes = form.getResources();
			Integer[] selectedIds = form.getSelectedIds();
			String unlockedUsers = null;
			int unlockedUsersCount = 0;
			

			for (int i = 0; i < selectedIds.length; i++) {
				VKCUser unlockUser = VKCUserSerializer.retrieveUser(selectedIds[i]);
				if(unlockUser.getPwdMismatchCount()>=3){
    				unlockUser.setAccountValid(true);
    				unlockUser.setLastChanged(new Timestamp(System.currentTimeMillis()));
    				unlockUser.setLastChangerId(user.getUserId());
    				unlockUser.setPwdMismatchCount(new Integer(0));
    				if(unlockUser.getValidFrom().after(new Date())){
    				    unlockUser.setValidFrom(null);
    				}
    				VKCUserSerializer.saveUser(unlockUser);
    
    				if (unlockedUsers == null) {
    					unlockedUsers = unlockUser.getUser();
    				} else {
    					unlockedUsers += ", " + unlockUser.getUser();
    				}
    				unlockedUsersCount++;
				}
				
			}

			if (selectedIds.length > 0) {
				if (selectedIds.length == 1) {
					infoString = infoString
							+ unlockedUsersCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.userList.unlockUser.done")
							+ " " + unlockedUsers + "\\n";
				} else {
					infoString = infoString
							+ unlockedUsersCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.userList.unlockUsers.done")
							+ " " + unlockedUsers + "\\n";
				}
			}

			request.setAttribute(WebShare.MESSAGE_KEY, infoString);

			return handleInitializeAction(form, request);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}
	private ActionForward handleEnableUsersAction(UserListForm form, HttpServletRequest request) throws ServletException {
        try {
            VKCUser user = form.getUser();
            Locale locale = user.getLanguage().getLocale();
            MessageResources mRes = form.getResources();
            Integer[] selectedIds = form.getSelectedIds();
            String unlockedUsers = null;
            int unlockedUsersCount = 0;

            for (int i = 0; i < selectedIds.length; i++) {
                VKCUser unlockUser = VKCUserSerializer.retrieveUser(selectedIds[i]);
                unlockUser.setAccountValid(true);
                unlockUser.setLastChanged(new Timestamp(System.currentTimeMillis()));
                unlockUser.setLastChangerId(user.getUserId());
                VKCUserSerializer.saveUser(unlockUser);

                if (unlockedUsers == null) {
                    unlockedUsers = unlockUser.getUser();
                } else {
                    unlockedUsers += ", " + unlockUser.getUser();
                }

                unlockedUsersCount++;
            }

            if (selectedIds.length > 0) {
                if (selectedIds.length == 1) {
                    infoString = infoString
                            + unlockedUsersCount
                            + " "
                            + mRes.getMessage(locale, "vkc.administration.userList.unlockUser.done")
                            + " " + unlockedUsers + "\\n";
                } else {
                    infoString = infoString
                            + unlockedUsersCount
                            + " "
                            + mRes.getMessage(locale, "vkc.administration.userList.unlockUsers.done")
                            + " " + unlockedUsers + "\\n";
                }
            }

            request.setAttribute(WebShare.MESSAGE_KEY, infoString);

            return handleInitializeAction(form, request);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }


	private ActionForward handleInitializeAction(UserListForm form, HttpServletRequest request) throws ServletException {
		try {
			form.setSelectedIds(new Integer[0]);

			return DEFAULT_FORWARD;
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	private ActionForward handleChangeSortMode(UserListForm form, HttpServletRequest request) {
		form.setSelectedIds(new Integer[0]);
		form.setListIndex(new Integer(0));

		return DEFAULT_FORWARD;
	}
}