/*
 * $Id: SystemDefaultsAction.java,v 1.14 2006/10/04 03:14:59 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 *$Log: SystemDefaultsAction.java,v $
 *Revision 1.14  2006/10/04 03:14:59  marbobo
 *+ Vollständige Unterstützung für Templates implementiert
 *+ Alles von Virtoweb auf ProCoBa umgestellt
 *
 *Revision 1.13  2006/09/11 14:34:05  marbobo
 *+ "Registerkarteneinstellungen" etwas überarbeitet
 *
 *Revision 1.12  2005/08/25 01:43:40  marbobo
 *+ Permanente Registerkarten hinzugefügt
 *
 *Revision 1.11  2005/08/09 19:48:55  marbobo
 *+ Eigenschaften von registerkarten ändern implementiert
 *
 *Revision 1.10  2005/02/20 16:56:23  marbobo
 *+ Beim Speichern der Entities in die Datenbank wird sichergestellt
 *   dass Unicode-Zeichen in Kodierterform (als &#xxxxx;) gespeichert werden
 *
 *Revision 1.9  2005/02/14 14:01:47  bigmac
 *Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 *Revision 1.8  2004/12/13 19:21:04  marbobo
 *+ Bugfix
 *
 *Revision 1.7  2004/12/13 19:19:12  marbobo
 *+ Standardsprache festlegen
 *
 *Revision 1.6  2004/09/16 13:10:55  marbobo
 *+ Auf VKCRequestProcessor umgestellt
 *
 *Revision 1.5  2004/07/20 08:05:26  jonyp
 *added copyright info + cvs log
 *
 *Revision 1.4  2004/05/10 10:44:51  marbobo
 *+ Anker
 *
 *Revision 1.3  2004/05/06 22:13:17  marbobo
 *+ AddCatAttributes- und AddDocAttributes-Managment
 *
 *Revision 1.2  2004/05/06 13:20:59  marbobo
 *+ Einige Ergänzungen
 *
 *Revision 1.1  2004/05/05 22:16:48  marbobo
 *Initiale Version
 *
 */

package vkc.administration.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

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 vkc.administration.form.SystemDefaultsForm;
import vkc.db.entities.VKCAddAttribute;
import vkc.db.entities.VKCDocumentViewField;
import vkc.db.entities.VKCLanguage;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCAddAttributeSerializer;
import vkc.db.serializer.VKCDocumentViewFieldSerializer;
import vkc.db.serializer.VKCLanguageSerializer;
import vkc.db.serializer.VKCTabViewSerializer;
import vkc.exception.DBException;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;
import vkc.view.bean.TabInfo;

public class SystemDefaultsAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/administration/systemDefaults.jsp");

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

	public ActionForward execute( ActionMapping mapping,
								  ActionForm f, 
								  HttpServletRequest request, 
								  HttpServletResponse response )
	throws ServletException {

		try {
			SystemDefaultsForm form = (SystemDefaultsForm)f;
			VKCUser user = form.getUser();

			if (!user.hasAdminPrivileges()) {
				request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");
				
				return INFO_FORWARD;
			}
	
			if (request.getParameter("action.save.documentview") != null) {
				return handleSaveDocumentViewAction(form, request);
			} else if (request.getParameter("action.new.addcatattribute") != null) {
				return handleNewAddCatAttributeAction(form, request);
			} else if (request.getParameter("action.delete.addcatattribute") != null) {
				return handleDeleteAddCatAttributeAction(form, request);
			} else if (request.getParameter("action.save.addcatattributes") != null) {
				return handleSaveAddCatAttributeAction(form, request);
			} else if (request.getParameter("action.new.adddocattribute") != null) {
				return handleNewAddDocAttributeAction(form, request);
			} else if (request.getParameter("action.delete.adddocattribute") != null) {
				return handleDeleteAddDocAttributeAction(form, request);
			} else if (request.getParameter("action.save.adddocattributes") != null) {
				return handleSaveAddDocAttributeAction(form, request);
			} else if (request.getParameter("action.save.defaultlanguage") != null) {
				return handleSaveDefaultLanguageAction(form, request);
			} else if (request.getParameter("action.save.tabviewsettings") != null) {
				return handleSaveTabViewSettingsAction(form, request);
			} else {
				return handleInitializeAction( form, request );
			}
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
	
	private ActionForward handleSaveDefaultLanguageAction(SystemDefaultsForm form, HttpServletRequest request) throws DBException {
        List languages = form.getLanguages();
        
        for (int i = 0; i < languages.size(); i++) {
            VKCLanguage language = (VKCLanguage)languages.get(i);
            
            if (language.getLanguageId().equals(form.getSelectedId())) {
                language.setDefaultLanguage(new Integer(1));
            } else {
                language.setDefaultLanguage(new Integer(0));
            }
        }
        
        VKCLanguageSerializer.saveLanguage(languages);

		return handleInitializeAction(form, request);
    }

    private ActionForward handleNewAddCatAttributeAction(SystemDefaultsForm form, HttpServletRequest request) {
		VKCAddAttribute attribute = new VKCAddAttribute();
		attribute.setAttrId(new Integer(-form.getUniqueId().intValue()));
		
		form.getAddCatAttributes().add(attribute);
		
		form.setUniqueId(new Integer(form.getUniqueId().intValue() + 1));
		
		return new ActionForward("/templates/${template.name}/administration/systemDefaults.jsp?anchor=attribute" + attribute.getAttrId());
	}

	private ActionForward handleDeleteAddCatAttributeAction(SystemDefaultsForm form, HttpServletRequest request) {
		List ids = new ArrayList(Arrays.asList(form.getSelectedIds()));
		HashSet deleteIds = new HashSet(Arrays.asList(form.getDeleteIds()));
		List addCatAttributes = form.getAddCatAttributes();
		List attributes = new ArrayList();
		
		for (int i = 0; i < addCatAttributes.size(); i++) {
			VKCAddAttribute attribute = (VKCAddAttribute)addCatAttributes.get(i);
			
			if (!ids.contains(attribute.getAttrId())) {
				attributes.add(attribute);		
			} else {
				deleteIds.add(attribute.getAttrId());
			}
		}
		
		form.setAddCatAttributes(attributes);
		form.setSelectedIds(new Integer[0]);
		form.setDeleteIds((Integer[])deleteIds.toArray(new Integer[0]));
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleSaveAddCatAttributeAction(SystemDefaultsForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList(Arrays.asList(form.getNullIds()));
		List addCatAttributes = form.getAddCatAttributes();
		
		for (int i = 0; i < addCatAttributes.size(); i++) {
			VKCAddAttribute attribute = (VKCAddAttribute)addCatAttributes.get(i);
			
			if (ids.contains(attribute.getAttrId())) {
				attribute.setAllowNull(null);		
			} else {
				attribute.setAllowNull(new Integer(1));		
			}
			
			attribute.setName(VKCStringUtils.filterUnicodeChars(attribute.getName()));
			attribute.setDescription(VKCStringUtils.filterUnicodeChars(attribute.getDescription()));
			attribute.setDefaultValue(VKCStringUtils.filterUnicodeChars(attribute.getDefaultValue()));
		}
		
		VKCAddAttributeSerializer.deleteAddCatAttribute(form.getDeleteIds());
		VKCAddAttributeSerializer.saveAddCatAttribute(addCatAttributes);
		
		form.setDeleteIds(new Integer[0]);
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleNewAddDocAttributeAction(SystemDefaultsForm form, HttpServletRequest request) {
		VKCAddAttribute attribute = new VKCAddAttribute();
		attribute.setAttrId(new Integer(-form.getUniqueId().intValue()));
		
		form.getAddDocAttributes().add(attribute);
		
		form.setUniqueId(new Integer(form.getUniqueId().intValue() + 1));
		
		return new ActionForward("/templates/${template.name}/administration/systemDefaults.jsp?anchor=attribute" + attribute.getAttrId());
	}

	private ActionForward handleDeleteAddDocAttributeAction(SystemDefaultsForm form, HttpServletRequest request) {
		List ids = new ArrayList(Arrays.asList(form.getSelectedIds()));
		HashSet deleteIds = new HashSet(Arrays.asList(form.getDeleteIds()));
		List addDocAttributes = form.getAddDocAttributes();
		List attributes = new ArrayList();
		
		for (int i = 0; i < addDocAttributes.size(); i++) {
			VKCAddAttribute attribute = (VKCAddAttribute)addDocAttributes.get(i);
			
			if (!ids.contains(attribute.getAttrId())) {
				attributes.add(attribute);
			} else {
				deleteIds.add(attribute.getAttrId());
			}
		}
		
		form.setAddDocAttributes(attributes);
		form.setSelectedIds(new Integer[0]);
		form.setDeleteIds((Integer[])deleteIds.toArray(new Integer[0]));
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleSaveAddDocAttributeAction(SystemDefaultsForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList(Arrays.asList(form.getNullIds()));
		List addDocAttributes = form.getAddDocAttributes();
		
		for (int i = 0; i < addDocAttributes.size(); i++) {
			VKCAddAttribute attribute = (VKCAddAttribute)addDocAttributes.get(i);
			
			if (ids.contains(attribute.getAttrId())) {
				attribute.setAllowNull(null);		
			} else {
				attribute.setAllowNull(new Integer(1));		
			}

			attribute.setName(VKCStringUtils.filterUnicodeChars(attribute.getName()));
			attribute.setDescription(VKCStringUtils.filterUnicodeChars(attribute.getDescription()));
			attribute.setDefaultValue(VKCStringUtils.filterUnicodeChars(attribute.getDefaultValue()));
		}
		
		VKCAddAttributeSerializer.deleteAddDocAttribute(form.getDeleteIds());
		VKCAddAttributeSerializer.saveAddDocAttribute(addDocAttributes);
		
		form.setDeleteIds(new Integer[0]);

		return DEFAULT_FORWARD;
	}

	private ActionForward handleInitializeAction(SystemDefaultsForm form, HttpServletRequest request) throws DBException {
		if (request.getParameter("selectedContext") == null) {
			// Default-Context setzen
			form.setSelectedContext(SystemDefaultsForm.DOCUMENTVIEWFIELDS);
		}
		
		if (form.getSelectedContext().equals(SystemDefaultsForm.DEFAULTLANGUAGES)) {
	        List languages = form.getLanguages();
	        
	        for (int i = 0; i < languages.size(); i++) {
	            VKCLanguage language = (VKCLanguage)languages.get(i);
	            
	            if (language.isDefaultLanguage()) {
	                form.setSelectedId(language.getLanguageId());
	                break;
	            }
	        }
		} else if (form.getSelectedContext().equals(SystemDefaultsForm.DOCUMENTVIEWFIELDS)) {
			List ids = new ArrayList();
			Iterator it = VKCDocumentViewFieldSerializer.getAllDocumentViewFields().values().iterator();
			
			form.setSelectedIds(new Integer[0]);
			
			while (it.hasNext()) {
				VKCDocumentViewField field = (VKCDocumentViewField)it.next();
				
				if (field.isDefaulField()) {
					ids.add(field.getFieldId());
				}
			}
			
			form.setDeleteIds(new Integer[0]);
			form.setSelectedIds((Integer[])ids.toArray(new Integer[0]));
		} else if (form.getSelectedContext().equals(SystemDefaultsForm.ADDCATATTRIBUTES)) {
			List ids = new ArrayList();
			form.setAddCatAttributes(new ArrayList(VKCAddAttributeSerializer.getAllAddCatAttributes()));

			for (int i = 0; i < form.getAddCatAttributes().size(); i ++) {
				VKCAddAttribute attribute = (VKCAddAttribute)form.getAddCatAttributes().get(i);
				
				if (attribute.getAllowNull() == null || attribute.getAllowNull().intValue() == 0) {
					ids.add(attribute.getAttrId());
				}
			}

			form.setDeleteIds(new Integer[0]);
			form.setSelectedIds(new Integer[0]);
			form.setNullIds((Integer[])ids.toArray(new Integer[0]));
		} else if (form.getSelectedContext().equals(SystemDefaultsForm.ADDDOCATTRIBUTES)) {
			List ids = new ArrayList();
			form.setAddDocAttributes(new ArrayList(VKCAddAttributeSerializer.getAllAddDocAttributes()));

			for (int i = 0; i < form.getAddDocAttributes().size(); i ++) {
				VKCAddAttribute attribute = (VKCAddAttribute)form.getAddDocAttributes().get(i);
				
				if (attribute.getAllowNull() == null || attribute.getAllowNull().intValue() == 0) {
					ids.add(attribute.getAttrId());
				}
			}

			form.setDeleteIds(new Integer[0]);
			form.setSelectedIds(new Integer[0]);
			form.setNullIds((Integer[])ids.toArray(new Integer[0]));
		} else if (form.getSelectedContext().equals(SystemDefaultsForm.TABVIEWSETTINGS)) {
			List ids = new ArrayList();

			TabInfo tab = form.getTabView(form.getSelectedTabViewId().toString());
			
			if (tab != null) {
				form.setSelectedId(tab.getViewTypeId());
				
				if (tab.isEnabled()) {
					ids.add(tab.getTabId());
				}

				form.setSelectedIds((Integer[])ids.toArray(new Integer[0]));
			}
		}

		return DEFAULT_FORWARD;
	}

	private ActionForward handleSaveDocumentViewAction(SystemDefaultsForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList(Arrays.asList(form.getSelectedIds()));
		Iterator it = VKCDocumentViewFieldSerializer.getAllDocumentViewFields().values().iterator();
			
		while (it.hasNext()) {
			VKCDocumentViewField field = (VKCDocumentViewField)it.next();
				
			if (ids.contains(field.getFieldId())) {
				field.setDefaulField(true);
			} else {
				field.setDefaulField(false);
			}
			
			VKCDocumentViewFieldSerializer.saveDocumentViewField(field);
		}
		
		return handleInitializeAction(form, request);
	}

    private ActionForward handleSaveTabViewSettingsAction(SystemDefaultsForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList(Arrays.asList(form.getSelectedIds()));
		TabInfo pTab = WebShare.getPermanentTabView(form.getSelectedTabViewId());
		
    	if (pTab == null) {
			TabInfo tab = form.getTabView(form.getSelectedTabViewId().toString());
			
			tab.setViewTypeId(form.getSelectedId());
			
			if (ids.isEmpty()) {
				tab.setEnabled(false);
			} else {
				for (int i = 0; i < ids.size(); i++) {
					Integer id = (Integer)ids.get(i);
					
					if (tab.getTabId().equals(id)) {
						tab.setEnabled(true);
						break;
					}
				}
			}
			
			VKCTabViewSerializer.saveTabView(tab);
		} else {
			form.setSelectedId(pTab.getViewTypeId());
			
			if (pTab.isEnabled()) {
				ids.add(pTab.getTabId());
			} else {
				ids.remove(pTab.getTabId());
			}
			
			form.setSelectedIds((Integer[])ids.toArray(new Integer[0]));
		}

		return DEFAULT_FORWARD;
	}
}