/*
 * $Id$
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log$
 * Revision 1.1  2006/04/29 18:34:43  marbobo
 * + Initiale Version
 *
 */
package vkc.administration.form;

import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

import vkc.db.helper.UserHelper;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.util.StringUtils;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;
import vkc.view.bean.UserInfo;
import vkc.view.bean.UserStatistics;
import vkc.view.bean.VKCQuotaInfo;
import vkc.view.form.DynaForm;

/**
 * Form Bean zum Löschen von Benutzerprofilen
 *
 * @author marbobo
 */
public final class DeleteUsersForm extends DynaForm {
	private HashMap newPublisherInfos = new HashMap();

	private Integer loggedUserId = null;
	
	private Integer[] deletedUserIds = new Integer[0];
	private Integer[] lockedUserIds = new Integer[0];
	
	private List publisherInfos = null;

	private String redirect = "";
	
	/**
	 * Reset der Eingabefelder auf Defaultwerte
	 *
	 * @param mapping The mapping used to select this instance
	 * @param request The servlet request we are processing
	 */
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		super.reset(mapping, request);

		newPublisherInfos = new HashMap();

		loggedUserId = null;

		deletedUserIds = new Integer[0];
		lockedUserIds = new Integer[0];

		publisherInfos = null;

		redirect = "";
	}

	/**
	 * Validiert die Eingabefelder und gibt gegebenfalls die Fehler zurück
	 *
	 * @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();
		
		if (request.getParameter("initialize") != null) {
			HashSet ids = new HashSet();
			ids.addAll(Arrays.asList(getDeletedUserIds()));
			
			if (ids.remove(getUser().getUserId())) {
				setLoggedUserId(getUser().getUserId());
				setDeletedUserIds((Integer[])ids.toArray(new Integer[0]));
			} else {
				ids.clear();
				ids.addAll(Arrays.asList(getLockedUserIds()));
				
				if (ids.remove(getUser().getUserId())) {
					setLoggedUserId(getUser().getUserId());
					setLockedUserIds((Integer[])ids.toArray(new Integer[0]));
				}
			}

			for (int i = 0; i < getLockedUserIds().length; i++) {
				NewPublisher pub = new NewPublisher();
				pub.setUserId(getLockedUserIds()[i]);
				newPublisherInfos.put(getLockedUserIds()[i], pub);
			}
		}

		return errors;
	}

	public String getRedirect() {
	    return redirect;
	}
	
	public void setRedirect(String s) {
	    redirect = StringUtils.normalize(s);
	}

	public String getRedirectPath() {
	    if (!isEmpty(getRedirect())) {
		    return VKCStringUtils.base64Decode(getRedirect());
	    }
	    
	    return "/userList.do";
	}

	public Integer[] getDeletedUserIds() {
		return deletedUserIds;
	}

	public void setDeletedUserIds(Integer[] deleteUserIds) {
		this.deletedUserIds = deleteUserIds;
	}

	public Integer[] getLockedUserIds() {
		return lockedUserIds;
	}

	public void setLockedUserIds(Integer[] lockedUserIds) {
		this.lockedUserIds = lockedUserIds;
	}
	
	public List getDeletedUserInfos() throws DBException {
		final Collator collator = Collator.getInstance(getUser().getLanguage().getLocale());
		List users = new ArrayList();
		
		for (int i = 0; i < getDeletedUserIds().length; i++) {
			users.add(VKCUserSerializer.retrieveUserInfo(getDeletedUserIds()[i]));
		}
		
		Comparator lastname_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.getLastname()));
            	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u2.getLastname()));
            	
            	return key1.compareTo(key2);
            }
        };

        Collections.sort(users, lastname_c);
        
        return users;
	}

	public List getLockedUserInfos() throws DBException {
		final Collator collator = Collator.getInstance(getUser().getLanguage().getLocale());
		List users = new ArrayList();
		
		for (int i = 0; i < getLockedUserIds().length; i++) {
			users.add(VKCUserSerializer.retrieveUserInfo(getLockedUserIds()[i]));
		}
		
		Comparator lastname_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.getLastname()));
            	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u2.getLastname()));
            	
            	return key1.compareTo(key2);
            }
        };

        Collections.sort(users, lastname_c);
        
        return users;
	}

	public Integer getLoggedUserId() {
		return loggedUserId;
	}

	public void setLoggedUserId(Integer loggedUserId) {
		this.loggedUserId = loggedUserId;
	}

	public List getPublisherInfos() throws DBException {
		if (publisherInfos == null) {
			publisherInfos = VKCUserSerializer.retrieveUserInfos();
			final Collator collator = Collator.getInstance(getUser().getLanguage().getLocale());
			
			Comparator lastname_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.getLastname()));
	            	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u2.getLastname()));
	            	
	            	return key1.compareTo(key2);
	            }
	        };

	        for (int i = 0; i < getDeletedUserIds().length; i++) {
				UserInfo user = new UserInfo(getDeletedUserIds()[i]);
				publisherInfos.remove(user);
			}

	        for (int i = 0; i < getLockedUserIds().length; i++) {
				UserInfo user = new UserInfo(getLockedUserIds()[i]);
				publisherInfos.remove(user);
			}

	        Collections.sort(publisherInfos, lastname_c);
		}
		
		return publisherInfos;
	}
	
	public HashMap getNewPublisherInfos() {
		return newPublisherInfos;
	}

	public NewPublisher getNewPublisher(int index) {
		NewPublisher pub = (NewPublisher)newPublisherInfos.get(new Integer(index));
		
		if (pub == null) {
			pub = new NewPublisher();
			pub.setUserId(new Integer(index));
			newPublisherInfos.put(new Integer(index), pub);
		}
		
		return pub;
	}

	public VKCQuotaInfo getUserQuota(String id) throws DBException {
		return WebShare.database.getQuotaInfo(Integer.valueOf(id), true);
    }

    public UserStatistics getUserStatistics(String id) throws DBException {
    	return UserHelper.getUserStatistics(Integer.valueOf(id));
    }
	
	public void setNewPublisher(int index, NewPublisher pub) {
		newPublisherInfos.put(new Integer(index), pub);
	}

	public Integer getDeletedUserIdsCount() {
		return new Integer(getDeletedUserIds().length);
	}
	
	public Integer getLockedUserIdsCount() {
		return new Integer(getLockedUserIds().length);
	}
	
	public boolean isDeleteUsers() {
		return getDeletedUserIds().length > 0 || getLockedUserIds().length > 0;
	}
	
	public class NewPublisher {
		private Integer id = getUser().getUserId();
		private Integer userId = null;

		public Integer getId() {
			return id;
		}

		public void setId(Integer id) {
			this.id = id;
		}

		public Integer getUserId() {
			return userId;
		}

		public void setUserId(Integer userId) {
			this.userId = userId;
		}
	}
}