/*
 * $Id: SystemParametersForm.java,v 1.21 2007/10/23 07:53:30 korowa Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: SystemParametersForm.java,v $
 * Revision 1.21  2007/10/23 07:53:30  korowa
 * MigrationLog hinzugefügt
 *
 * Revision 1.20  2007/08/01 14:56:47  marbobo
 * + WebDav-Logging implementiert
 * - Sessionbegrenzung wird nicht mehr auf WebDav angewendet
 *
 * Revision 1.19  2006/07/19 23:13:29  marbobo
 * + Kontextnamen sortieren
 *
 * Revision 1.18  2005/12/15 15:28:52  marbobo
 * + Benutzername und Passwort für Mailserver implementiert
 *
 * Revision 1.17  2005/08/24 18:36:30  marbobo
 * + Bugfix
 *
 * Revision 1.16  2005/08/24 13:40:21  marbobo
 * + Versteckte Parameter nicht anzeigen
 *
 * Revision 1.15  2004/11/10 15:02:48  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.14  2004/09/16 13:10:55  marbobo
 * + Auf VKCRequestProcessor umgestellt
 *
 * Revision 1.13  2004/08/30 14:45:49  koppy
 * WORKFLOW context anhand vkc.workflow.enabled ein-/ausblenden
 *
 * Revision 1.12  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.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
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.VKCSysParameter;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.misc.VKCLogManager;
import vkc.util.StringUtils;
import vkc.util.VKCStringUtils;
import vkc.view.InputFieldConstraints;
import vkc.view.WebShare;
import vkc.view.form.BasicActionForm;

public class SystemParametersForm extends BasicActionForm {
	public static final Integer VIEW_MODE_PARAMETERS    = new Integer(0);
	public static final Integer VIEW_MODE_FILE     		= new Integer(1);

	private HashMap contextNameKeys = new HashMap();

	private Integer selectedParamterId = new Integer(-1);
	private Integer viewMode = VIEW_MODE_PARAMETERS;

	private List    contextNames = new ArrayList();
	private List    systemParameters = null;

	private String  selectedContext = "";
	
	public void reset(ActionMapping mapping, HttpServletRequest request) {
	    super.reset(mapping, request);
	    
		try {
			systemParameters = 	VKCSysParameterSerializer.retrieveParameters();
			contextNames = VKCSysParameterSerializer.retrieveContextNames();
			contextNameKeys = VKCSysParameterSerializer.retrieveContextNameKeys();
			viewMode = VIEW_MODE_PARAMETERS;
			selectedParamterId = new Integer(-1);
			contextNames = sortContextNames(contextNames);

			if (!WebShare.getProperties().getProperty("vkc.workflow.enabled", "false").equalsIgnoreCase("true")) {
			    contextNames.remove("WORKFLOW");
			}
		} catch(Exception ex) {
			VKCLogManager.errorLog(this, "1", "reset() failed!", ex);
		}
	}

	public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();

		if (request.getParameter("action.save") != null) {
			int i=0;
			
			while (request.getParameter("parameter[" + i + "].name") != null) {
				String name = request.getParameter("parameter[" + i + "].name");
				String value = request.getParameter("parameter[" + i + "].valuestring");
	
				VKCSysParameter sysParam = findParam(getSelectedContext(), name);
				sysParam.setValuestring(StringUtils.normalize(value));
				
				if (!sysParam.isReadOnly()) {
					if (sysParam.isIntegerType()) {
						if (!isEmpty(sysParam.getValuestring()) && !isParsableInteger(sysParam.getValuestring())) {
							// Wert ist kein Integer 
							errors.add(name, new ActionError("sysparam.error.number.invalid", sysParam.getName()));
						}
						
						if (!sysParam.getAllowNull() && isEmpty(sysParam.getValuestring())) {
							// Feld darf nicht leer sein 
							errors.add(name, new ActionError("sysparam.error.empty.value", sysParam.getName()));						
						}
					}

					if (sysParam.isStringType()) {
					  	if (!isLengthValid(sysParam.getValuestring(), "sysparameter.valuestring")) {
							// Wert ist zu lang für das Datenbankfeld 
							errors.add(name, new ActionError("sysparam.error.length.invalid", new String[] {sysParam.getName(), InputFieldConstraints.getMaxLength("sysparameter.valuestring")}));						
						} else if (!sysParam.getAllowNull() && isEmpty(sysParam.getValuestring())) {
							// Feld darf nicht leer sein 
							errors.add(name, new ActionError("sysparam.error.empty.value", sysParam.getName()));						
						}
					}
				}
				
				i++;
			}
		}

		return errors;
	}

	public VKCSysParameter findParam(String context, String name) {
		for (Iterator iter = getSystemParameters().iterator(); iter.hasNext();) {
			VKCSysParameter param = (VKCSysParameter)iter.next();
			
			if (param.getContext().equals(context) && param.getName().equals(name)) {
				return param;
			}
		}
		
		return null;
	}
	
	public VKCSysParameter findParam(Integer id) {
		for (Iterator iter = getSystemParameters().iterator(); iter.hasNext();) {
			VKCSysParameter param = (VKCSysParameter)iter.next();
			
			if (param.getSysParameterId().equals(id)) {
				return param;
			}
		}
		
		return null;
	}
	
	public String getSelectedContext() {
		return selectedContext;
	}

	public void setSelectedContext(String context) {
		selectedContext = context;
	}

	public boolean isSelectedContextEditable() {
		for (Iterator iter = getSelectedContextParameters().iterator(); iter.hasNext();) {
			VKCSysParameter param = (VKCSysParameter)iter.next();
			
			if (!param.isReadOnly()) {
				return true;
			}
		}

		return false;
	}

	public List getSelectedContextParameters() {
		ArrayList list = new ArrayList();
		Integer zero = new Integer(0);

		for (Iterator iter = getSystemParameters().iterator(); iter.hasNext();) {
			VKCSysParameter param = (VKCSysParameter)iter.next();
			
			if (param.getContext().equalsIgnoreCase(getSelectedContext()) && zero.equals(param.getHide())) {
				list.add(param);
			}
		}
		
		return list;
	}

	public boolean getShowContextName(String contextName) {
		Integer zero = new Integer(0);
		
		for (Iterator iter = getSystemParameters().iterator(); iter.hasNext();) {
			VKCSysParameter param = (VKCSysParameter)iter.next();
			
			if (param.getContext().equals(contextName) && zero.equals(param.getHide())) {
				return true;
			}
		}
		
		return false;
	}
	
	public List getContextNames() {
		return contextNames;
	}

	public String getContextNameKey(String key) {
		return (String)contextNameKeys.get(key);
	}

	public List getSystemParameters() {
		return systemParameters == null ? new ArrayList() : systemParameters;
	}

	public Integer getViewMode() {
		return viewMode;
	}

	public void setViewMode(Integer integer) {
		viewMode = integer == null ? VIEW_MODE_PARAMETERS : integer;
	}
	
	public boolean getFileParameter( String parameterName ) {
		VKCSysParameter parameter = findParam(getSelectedContext(), parameterName);
		
		if (parameter == null) {
			return false;
		}
		
        if (parameter.getContext().equalsIgnoreCase("LOGGING") && parameter.getName().equalsIgnoreCase("WebdavAccessLogFile")) {
            return true;
        }
        
		if (parameter.getContext().equalsIgnoreCase("LOGGING") && parameter.getName().equalsIgnoreCase("AccessLogFile")) {
			return true;
		}
		
		if (parameter.getContext().equalsIgnoreCase("LOGGING") && parameter.getName().equalsIgnoreCase("ServerLogFile")) {
			return true;
		}
		
		if (parameter.getContext().equalsIgnoreCase("LOGGING") && parameter.getName().equalsIgnoreCase("InfoLogFile")) {
			return true;
		}
		
		if (parameter.getContext().equalsIgnoreCase("LOGGING") && parameter.getName().equalsIgnoreCase("ErrorLogFile")) {
			return true;
		}
		
		if (parameter.getContext().equalsIgnoreCase("LOGGING") && parameter.getName().equalsIgnoreCase("TraceLogFile")) {
			return true;
		}
		
		if (parameter.getContext().equalsIgnoreCase("LOGGING") && parameter.getName().equalsIgnoreCase("MigrationLogFile")) {
			return true;
		}
		
		return false;
	}

	public boolean getPasswordParameter( String parameterName ) {
		VKCSysParameter parameter = findParam(getSelectedContext(), parameterName);
		
		if (parameter == null) {
			return false;
		}
		
		if (parameter.getContext().equalsIgnoreCase("MAIL") && parameter.getName().equalsIgnoreCase("MailPassword")) {
			return true;
		}
		
		return false;
	}

	public Integer getSelectedParamterId() {
		return selectedParamterId;
	}

	public void setSelectedParamterId(Integer integer) {
		selectedParamterId = integer;
	}

	private List sortContextNames(List contextNames2) {
		if (contextNames2 != null && contextNames2.size() > 1) {
			List contextBeans = new ArrayList();
			
			for (Iterator iter = contextNames2.iterator(); iter.hasNext();) {
				String contextName = (String) iter.next();
				ContextNameKeyBean cnkb = new ContextNameKeyBean();
				cnkb.setName(contextName);
				cnkb.setNameKey(getContextNameKey(contextName));
				cnkb.setNameValue(getResources().getMessage(getUser().getLanguage().getLocale(), cnkb.getNameKey()));
				contextBeans.add(cnkb);
			}
			
			final Collator collator = Collator.getInstance(getUser().getLanguage().getLocale());

			Comparator c = new Comparator() {
                public int compare(Object o1, Object o2) {
                	ContextNameKeyBean cnkb1 = (ContextNameKeyBean)o1;
                	ContextNameKeyBean cnkb2 = (ContextNameKeyBean)o2;

                	CollationKey key1 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(cnkb1.getNameValue()));
                	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(cnkb2.getNameValue()));
                	
                	return key1.compareTo(key2);
                }
            };
			
            Collections.sort(contextBeans, c);
            List sortedContextNames = new ArrayList();
            
            for (int i = 0; i < contextBeans.size(); i++) {
            	ContextNameKeyBean cnkb = (ContextNameKeyBean)contextBeans.get(i);
				sortedContextNames.add(cnkb.getName());
			}
            
            return sortedContextNames;
		}
		
		return contextNames2;
	}
}

class ContextNameKeyBean {
	private String name = "";
	private String nameKey = "";
	private String nameValue = "";
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getNameKey() {
		return nameKey;
	}
	
	public void setNameKey(String nameKey) {
		this.nameKey = nameKey;
	}
	
	public String getNameValue() {
		return nameValue;
	}
	
	public void setNameValue(String nameValue) {
		this.nameValue = nameValue;
	}
}