/*
 * $Id$
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log$
 * Revision 1.2  2006/10/04 03:15:00  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.1  2006/04/29 18:34:43  marbobo
 * + Initiale Version
 *
 */
package vkc.administration.action;

import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

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.DeleteUsersForm;
import vkc.administration.form.DeleteUsersForm.NewPublisher;
import vkc.db.entities.VKCDocument;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;
import vkc.view.bean.UserInfo;

/**
 * Action-Klasse zum Löschen von Benutzer-Objekten
 *
 * @author marbobo
 */
public final class DeleteUsersAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/administration/deleteUsers.jsp");

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

	//~ Methods ----------------------------------------------------------------

	/**
	 * Hier werden die entsprechenden Aktionen eingeleitet
	 */
	public ActionForward execute(ActionMapping mapping, 
	        					 ActionForm f, 
	        					 HttpServletRequest request, 
	        					 HttpServletResponse response)
	throws Exception {
		DeleteUsersForm form = (DeleteUsersForm) f;
		VKCUser user = form.getUser();
		
		if (!user.hasAdminPrivileges() && !user.isDedicatedUsersAdmin()) {
            request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");
            
            return INFO_FORWARD;
        }

		//Aktionen bestimmen
		if (request.getParameter("action.cancel") != null) {
			return new ActionForward(form.getRedirectPath(), true);
		} else if (request.getParameter("action.execute") != null) {
			return handleExecuteAction(form, request);
		}

		return handleInitializeAction(form, request);
	}

	private ActionForward handleExecuteAction(DeleteUsersForm form, HttpServletRequest request) throws DBException {
		List users = form.getDeletedUserInfos();
		users.addAll(form.getLockedUserInfos());
		Integer[] ids = form.getLockedUserIds();
		
		for (int i = 0; i < ids.length; i++) {
		    List documents = new ArrayList(VKCDocumentSerializer.getDocuments(ids[i]));
		    NewPublisher pub = form.getNewPublisher(ids[i].intValue());
		    
		    for (Iterator iter = documents.iterator(); iter.hasNext();) {
				VKCDocument document = (VKCDocument) iter.next();
				
			    document.setPublisherId(pub.getId());
			    document.setLastChangerId(form.getUser().getUserId());
			    document.setLastChanged(new Date(System.currentTimeMillis()));
			    VKCDocumentSerializer.saveDocument(document, true, false);
			}
		    
		    VKCCategorySerializer.changeCreatorId(null, ids[i], pub.getId(), form.getUser().getUserId());
		    VKCUserSerializer.deleteUser(ids[i]);
		}
		
		ids = form.getDeletedUserIds();
		
		for (int i = 0; i < ids.length; i++) {
		    VKCUserSerializer.deleteUser(ids[i]);
		}
		
		final Collator collator = Collator.getInstance(form.getUser().getLanguage().getLocale());

		Comparator username_c = new Comparator() {
            public int compare(Object o1, Object o2) {
                UserInfo u1 = (UserInfo) o1;
                UserInfo u2 = (UserInfo) o2;
                
            	CollationKey key1 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u1.getUsername()));
            	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u2.getUsername()));
            	
            	return key1.compareTo(key2);
            }
        };

        Collections.sort(users, username_c);
    	String infoString = "";
		String deletedUsers = null;
		Locale locale = form.getUser().getLanguage().getLocale();
		MessageResources mRes = form.getResources();

		if (form.getLoggedUserId() != null) {
			infoString = infoString
					+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.loggedUser")
					+ "\\n";
		}
		
		for (Iterator iter = users.iterator(); iter.hasNext();) {
			UserInfo user = (UserInfo) iter.next();
			
			if (deletedUsers == null) {
				deletedUsers = user.getUsername();
			} else {
				deletedUsers += ", " + user.getUsername();
			}
		}
		
		if (users.size() > 0) {
			if (users.size() == 1) {
				infoString = infoString
						+ users.size()
						+ " "
						+ mRes.getMessage(locale, "vkc.administration.userList.deleteUser.done")
						+ " " + deletedUsers + "\\n";
			} else {
				infoString = infoString
						+ users.size()
						+ " "
						+ mRes.getMessage(locale, "vkc.administration.userList.deleteUsers.done")
						+ " " + deletedUsers + "\\n";
			}
		}
		
		String path = form.getRedirectPath() + "&infoMessage=" + VKCStringUtils.base64Encode(infoString);

		return new ActionForward(path, true);
	}

	private ActionForward handleInitializeAction(DeleteUsersForm form, HttpServletRequest request) {
		return DEFAULT_FORWARD;
	}
}