/*
 * $Id: GroupListAction.java,v 1.22 2006/10/04 03:15:01 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: GroupListAction.java,v $
 * Revision 1.22  2006/10/04 03:15:01  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.21  2006/04/29 18:39:49  marbobo
 * + Refactoriengs und eine Ausgaben vereinheitlicht
 *
 * Revision 1.20  2005/02/16 23:00:32  marbobo
 * + Suche auf Unicode-Zeichen erweitert
 *
 * Revision 1.19  2005/02/14 14:01:47  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.18  2004/11/10 15:02:50  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.17  2004/09/16 13:10:54  marbobo
 * + Auf VKCRequestProcessor umgestellt
 *
 * Revision 1.16  2004/08/12 21:41:24  marbobo
 * + Actions auf Requestparameter umgestellt
 * + Bugfixes und Quellcode maintenance
 *
 * Revision 1.15  2004/07/20 08:05:19  jonyp
 * added copyright info + cvs log
 *
 */
package vkc.administration.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
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.GroupListForm;
import vkc.db.entities.VKCGroup;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCGroupSerializer;
import vkc.misc.VKCLogManager;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;
import vkc.view.bean.GroupInfo;

public class GroupListAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/administration/groupList.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 {
			GroupListForm form = (GroupListForm) f;
			VKCUser user = form.getUser();

			if (!user.hasAdminPrivileges() && !user.getManageOwnGroups()) {
				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.groupsperpage") != null) {
				form.setSelectedIds(new Integer[0]);
				form.setListIndex(new Integer(0));

				return DEFAULT_FORWARD;
			} else if (request.getParameter("action.delete.groups") != null) {
				return handleDeleteGroupsAction(form, request);
			} else if (request.getParameter("action.lock.groups") != null) {
				return handleLockGroupsAction(form, request);
			} else if (request.getParameter("action.unlock.groups") != null) {
				return handleUnlockGroupsAction(form, request);
			} else if (request.getParameter("action.search.redirect") != null) {
				form.setSearchQuery(VKCStringUtils.base64Decode(form.getSearchQuery()));

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

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

			for (int i = 0; i < selectedIds.length; i++) {
				VKCGroup unlockGroup = VKCGroupSerializer.retrieveGroup(selectedIds[i]);
				unlockGroup.setAccountValid(Boolean.TRUE);
				unlockGroup.setLastChanged(new Timestamp(System.currentTimeMillis()));
				unlockGroup.setLastChangerId(user.getUserId());
				VKCGroupSerializer.saveGroup(unlockGroup);

				if (unlockGroups == null) {
					unlockGroups = unlockGroup.getName();
				} else {
					unlockGroups += ", " + unlockGroup.getName();
				}

				unlockGroupsCount++;
			}

			if (selectedIds.length > 0) {
				if (unlockGroupsCount == 1) {
					infoString = infoString
							+ unlockGroupsCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.groupList.unlockGroup.done")
							+ " " + unlockGroups + "\\n";
				} else {
					infoString = infoString
							+ unlockGroupsCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.groupList.unlockGroups.done")
							+ " " + unlockGroups + "\\n";
				}
			}

			request.setAttribute(WebShare.MESSAGE_KEY, infoString);

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

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

			for (int i = 0; i < selectedIds.length; i++) {
				VKCGroup lockGroup = VKCGroupSerializer.retrieveGroup(selectedIds[i]);
				lockGroup.setAccountValid(Boolean.FALSE);
				lockGroup.setLastChanged(new Timestamp(System.currentTimeMillis()));
				lockGroup.setLastChangerId(user.getUserId());
				VKCGroupSerializer.saveGroup(lockGroup);

				if (lockGroups == null) {
					lockGroups = lockGroup.getName();
				} else {
					lockGroups += ", " + lockGroup.getName();
				}

				lockGroupsCount++;
			}

			if (selectedIds.length > 0) {
				if (lockGroupsCount == 1) {
					infoString = infoString
							+ lockGroupsCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.groupList.lockGroup.done")
							+ " " + lockGroups + "\\n";
				} else {
					infoString = infoString
							+ lockGroupsCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.groupList.lockGroups.done")
							+ " " + lockGroups + "\\n";
				}
			}

			request.setAttribute(WebShare.MESSAGE_KEY, infoString);

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

	private ActionForward handleDeleteGroupsAction(GroupListForm form, HttpServletRequest request) throws ServletException {
		try {
			VKCUser user = form.getUser();
			Locale locale = user.getLanguage().getLocale();
			MessageResources mRes = form.getResources();
			Integer[] selectedIds = form.getSelectedIds();
			String deletedGroups = null;
			HashMap groupMap = new HashMap();
			GroupInfo[] groups = form.getGroupInfos();
			int visibleGroupsCount = form.getVisibleGroupInfoSizes().intValue();
			int deletedGroupsCount = 0;

			for (int i = 0; i < groups.length; i++) {
				groupMap.put(groups[i].getGroupId(), groups[i].getName());
			}

			for (int i = 0; i < selectedIds.length; i++) {
				VKCGroupSerializer.deleteGroup(selectedIds[i]);

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

				deletedGroupsCount++;
			}

			if (selectedIds.length > 0) {
				if (deletedGroupsCount == 1) {
					infoString = infoString
							+ deletedGroupsCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.groupList.deleteGroup.done")
							+ " " + deletedGroups + "\\n";
				} else {
					infoString = infoString
							+ deletedGroupsCount
							+ " "
							+ mRes.getMessage(locale, "vkc.administration.groupList.deleteGroups.done")
							+ " " + deletedGroups + "\\n";
				}
			}

			if (deletedGroupsCount >= visibleGroupsCount) {
				int listIndex = form.getListIndex().intValue();
				listIndex -= form.getGroupsPerPage().intValue();

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

			if (deletedGroupsCount > 0) {
				form.setGroupInfos(null);
			}

			request.setAttribute(WebShare.MESSAGE_KEY, infoString);

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

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

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

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

		return DEFAULT_FORWARD;
	}
}