/*
 * $Id: NewUserForm.java,v 1.16 2006/02/27 16:16:18 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * $Log: NewUserForm.java,v $
 * Revision 1.16  2006/02/27 16:16:18  marbobo
 * + Systemsichten hinzugefügt
 * + SysLinks angepasst
 * + Benutzer können falls gewünscht Dokumentqueries anlegen
 *
 * Revision 1.15  2005/09/15 23:16:42  marbobo
 * + Sprachabhängiges Sortieren implementiert
 *
 * Revision 1.14  2005/02/20 23:34:14  marbobo
 * + Bugfix
 *
 * Revision 1.13  2004/12/14 10:11:42  jonyp
 * initialize menu-language box with default language
 *
 * Revision 1.12  2004/11/10 15:02:48  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.11  2004/09/01 13:52:32  marbobo
 * + Menüsprache wählbar
 * + Redirectadresse angepasst
 *
 * Revision 1.10  2004/08/07 00:34:43  marbobo
 * + Bugfix für Zeitangaben und Refactorings
 *
 * Revision 1.9  2004/07/20 08:09:56  jonyp
 * added copyright info + cvs log
 *
 */


package vkc.administration.form;

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

import javax.servlet.http.HttpServletRequest;

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

import vkc.db.entities.VKCLanguage;
import vkc.db.serializer.VKCLanguageSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.util.DateUtils;
import vkc.util.StringUtils;
import vkc.util.VKCStringUtils;
import vkc.view.PageId;
import vkc.view.form.BasicActionForm;

public final class NewUserForm extends BasicActionForm {
    private boolean accountActive	= false;
    private boolean allowManageSystemViewType = false;

	private Integer selectedLanguageId = null;
	private Integer selectedSystemViewTypeId = PageId.CATEGORY_VIEW;

	private String  email          	= "";
    private String  firstname      	= "";
    private String  lastname       	= "";
    private String  username       	= "";
    private String  validFrom		= "";
    private String  validUntil		= "";

    public void reset(ActionMapping mapping, HttpServletRequest request) {
        super.reset(mapping, request);

        accountActive	= false;
        allowManageSystemViewType = false;

    	selectedLanguageId = null;
    	selectedSystemViewTypeId = PageId.CATEGORY_VIEW;

    	email          	= "";
        firstname      	= "";
        lastname       	= "";
        username       	= "";
        validFrom		= "";
        validUntil		= "";
        
        // get default language
        selectedLanguageId = VKCLanguageSerializer.getDefaultLanguage().getLanguageId();
    }

    /**
     * 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();

		setAccountActive(request.getParameter("accountActive") != null);
		setAllowManageSystemViewType(request.getParameter("allowManageSystemViewType") != null);

		if (request.getParameter("action.create.user") != null) {
	        if (isEmpty(getUsername())) {
	            errors.add("username", new ActionError("vkc.administration.error.username.required"));
	        }
	
	        if (isEmpty(getFirstname())) {
	            errors.add("firstname", new ActionError("vkc.administration.error.firstname.required"));
	        }
	
	        if (isEmpty(getLastname())) {
	            errors.add("lastname", new ActionError("vkc.administration.error.lastname.required"));
	        }
	
	        if (isEmpty(getEmail()) || getEmail().length() < 6) {
	            errors.add("email", new ActionError("vkc.administration.error.email.required"));
	        }
	
	        if (isAccountActive()) {
	            Date f = DateUtils.parseDate(getValidFrom());
				Date u = DateUtils.parseDate(getValidUntil());
	
				if (!isEmpty(getValidFrom())) {
		            if (f == null) {
						errors.add("validFrom", new ActionError("error.date"));
		            }
				}
	
				if (!isEmpty(getValidUntil())) {
					if (u == null) {
						errors.add("validUntil", new ActionError("error.date"));
					}
				}
	
	            if (f != null && u != null && f.after(u)) {
	                errors.add("date", new ActionError("error.date.range"));
	            }
	        }
	
	        try {
	            if (VKCUserSerializer.isUserExistent(VKCStringUtils.filterUnicodeChars(getUsername()))) {
	                errors.add("username.exist", new ActionError("vkc.administration.error.username.exist"));
	            }
	        } catch (DBException e) {
	            VKCLogManager.errorLog(this, "", e.getMessage(), e);
	        }
		}

		return errors;
    }

    public boolean isAccountActive() {
        return accountActive;
    }

    public String getEmail() {
        return email;
    }

    public String getFirstname() {
        return firstname;
    }

    public List getLanguageLabels() {
		List languageLabels = VKCLanguageSerializer.getLanguages();
		final Collator collator = Collator.getInstance(getUser().getLanguage().getLocale());

		Comparator language_c = new Comparator() {
			public int compare(Object o1, Object o2) {
				VKCLanguage l1 = (VKCLanguage) o1;
				VKCLanguage l2 = (VKCLanguage) o2;
				
            	CollationKey key1 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(l1.getName()));
            	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(l2.getName()));
            	
            	return key1.compareTo(key2);
			}
		};

		Collections.sort(languageLabels, language_c);
        
		return languageLabels;
    }
    
    public String getLastname() {
        return lastname;
    }

	public Integer getSelectedLanguageId() {
		return selectedLanguageId;
	}

    public String getUsername() {
        return username;
    }

    public String getValidFrom() {
        return validFrom;
    }

    public String getValidUntil() {
        return validUntil;
    }

    public void setAccountActive(boolean b) {
        accountActive = b;
    }

    public void setEmail(String s) {
        email = StringUtils.normalize(s);
    }

    public void setFirstname(String s) {
        firstname = StringUtils.normalize(s);
    }

    public void setLastname(String s) {
        lastname = StringUtils.normalize(s);
    }

	public void setSelectedLanguageId(Integer integer) {
		selectedLanguageId = integer;
	}

    public void setUsername(String s) {
        username = StringUtils.normalize(s);
    }

    public void setValidFrom(String date) {
        validFrom = date;
    }

    public void setValidUntil(String date) {
        validUntil = date;
    }

	public boolean isAllowManageSystemViewType() {
		return allowManageSystemViewType;
	}

	public void setAllowManageSystemViewType(boolean allowManageSystemViewType) {
		this.allowManageSystemViewType = allowManageSystemViewType;
	}

	public Integer getSelectedSystemViewTypeId() {
		return selectedSystemViewTypeId;
	}

	public void setSelectedSystemViewTypeId(Integer selectedSystemViewTypeId) {
		this.selectedSystemViewTypeId = selectedSystemViewTypeId;
	}
	
	public boolean isHasPermission() {
		return getUser().hasAdminPrivileges() || (getUser().isDedicatedUsersAdmin() && getUser().isManageOwnUsersSystemViews());
	}
}