/*
 * $Id: EditCategoryForm.java,v 1.35 2006/10/29 17:25:31 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * $Log: EditCategoryForm.java,v $
 * Revision 1.35  2006/10/29 17:25:31  marbobo
 * + Überprüfung der Syntax für Suchanfragen
 *
 * Revision 1.34  2006/05/24 17:56:17  marbobo
 * + Toolbar des Html-Editors kann optional angezeigt oder verborgen werden
 *
 * Revision 1.33  2006/02/27 16:15:56  marbobo
 * + Systemsichten hinzugefügt
 * + SysLinks angepasst
 * + Benutzer können falls gewünscht Dokumentqueries anlegen
 *
 * Revision 1.32  2005/09/05 22:47:18  marbobo
 * + Suche nach Metadaten-Attribute (Erstellungsdatum) für Dokumente implementiert
 *
 * Revision 1.31  2004/11/10 15:02:47  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.30  2004/10/19 20:10:12  marbobo
 * + Bugfix beim validieren der Datumseingaben
 *
 * Revision 1.29  2004/10/19 19:58:39  marbobo
 * + Globale Kategorie-Attribute und Dyn. Attribute überarbeitet
 *
 * Revision 1.28  2004/10/06 12:33:36  marbobo
 * + Suche nach Globalen Dokument-Attributen korrigiert
 *
 * Revision 1.27  2004/10/05 17:59:46  marbobo
 * + Suche nach Globalen Dokument-Attributen überarbeitet
 *
 * Revision 1.26  2004/08/20 12:59:28  koppy
 * Anpassung an getLocalizedHTMLString(...)
 *
 * Revision 1.25  2004/07/20 08:53:51  jonyp
 * added copyright info + cvs log
 *
 */

package vkc.view.form;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

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

import vkc.db.entities.VKCAddAttribute;
import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCSearchQuery;
import vkc.db.serializer.VKCAddAttributeSerializer;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.search.Search;
import vkc.util.CategoryUtils;
import vkc.util.DateUtils;
import vkc.util.StringUtils;
import vkc.view.PageId;

public class EditCategoryForm extends DynaForm {
	public static final String EDITMODE_CATEGORY	= "EDITCATEGORY";
	public static final String EDITMODE_SEARCHQUERY	= "SEARCHQUERY";
	
    //~ Instance fields --------------------------------------------------------
    private HashMap addCatAttributes	= new HashMap();
	private HashMap	allAddCatAttributes	= null;

    private Integer categoryId 		= null;
    private Integer selectedIndex 	= new Integer(-1);
	private Integer sourcePageId 	= PageId.CATEGORY_VIEW;
	private Integer subTargetId 	= null;
	private Integer targetId 		= null;

    private List dynaAttributes = new ArrayList();
    
    private String description 			= "";
    private String editMode				= EDITMODE_CATEGORY;
	private String externalContacts 	= "";
    private String keywords 			= "";
	private String name 				= "";
    private String searchQuery 			= "";
    
    private VKCCategory category = null;

    private VKCSearchQuery query = new VKCSearchQuery();

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

	    addCatAttributes	= new HashMap();
		allAddCatAttributes	= null;

		categoryId 		= null;
	    selectedIndex 	= new Integer(-1);
		sourcePageId 	= PageId.CATEGORY_VIEW;
		subTargetId 	= null;
		targetId 		= null;

	    dynaAttributes = new ArrayList();

	    description 		= "";
	    editMode			= EDITMODE_CATEGORY;
		externalContacts 	= "";
	    keywords 			= "";
		name 				= "";
	    searchQuery 		= "";
	    
	    category = null;

	    query = new VKCSearchQuery();
    }

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

        try {
			synchronizeDynaAttributes(request);

			if (request.getParameter("action.save.searchquery") != null) {
				String from  = getQuery().getSearchForCreationDateFrom();
				String until = getQuery().getSearchForCreationDateUntil();
				Date f = null;
				Date u = null;
					
				if (!isEmpty(from)) {
					if ((f = DateUtils.parseDate(from)) == null) {
						errors.add("creationDateFrom", new ActionError("error.creation.date"));
						setEditMode(EDITMODE_SEARCHQUERY);
					}
				}

				if (!isEmpty(until)) {
					if ((u = DateUtils.parseDate(until)) == null) {
						errors.add("creationDateUntil", new ActionError("error.creation.date"));
						setEditMode(EDITMODE_SEARCHQUERY);
					}
				}
					
				if (f != null && u != null && f.after(u)) {
					errors.add("creationDate", new ActionError("error.date.range"));
					setEditMode(EDITMODE_SEARCHQUERY);
				}

				from  = getQuery().getValidFrom();
				until = getQuery().getValidUntil();
				f = null;
				u = null;
				
				if (!isEmpty(from)){
					if ((f = DateUtils.parseDate(from)) == null) {
						errors.add("validFrom", new ActionError("error.date"));
						setEditMode(EDITMODE_SEARCHQUERY);
					}
				}

				if (!isEmpty(until)){
					if ((u = DateUtils.parseDate(until)) == null) {
						errors.add("validUntil", new ActionError("error.date"));
						setEditMode(EDITMODE_SEARCHQUERY);
					}
				}
				
				if (f != null && u != null && f.after(u)) {
					errors.add("date", new ActionError("error.date.range"));
					setEditMode(EDITMODE_SEARCHQUERY);
				}
				
				if (!Search.parseSearchQuerySyntax(getQuery().getSearchQuery())) {
					errors.add("searchQuerySyntax", new ActionError("error.query.syntax"));
					setEditMode(EDITMODE_SEARCHQUERY);
				}
			}

			if (request.getParameter("action.save") != null) {
				if (isEmpty(getName())) {
					errors.add("name", new ActionError("error.category.name"));
				}

				VKCCategory category = getCategory();
				VKCCategory parentCategory = VKCCategorySerializer.retrieveCategory(category.getParentCategoryId());

				category.setName(getName());

				if (parentCategory != null) {
					if (!CategoryUtils.isCategoryNameUnique(category, parentCategory.getSubCategories())) {
						errors.add("name",	new ActionError("error.category.name.violation"));
					}
				}
				
                // check, if any global attribute must not be empty
                Iterator it = getAllAddCatAttributes().keySet().iterator();
                
                while (it.hasNext()) {
                    String key = (String)it.next();
                    VKCAddAttribute attr = (VKCAddAttribute)getAllAddCatAttributes().get(key);
                    
                    if (attr.getAllowNull().intValue() == 0 && isEmpty((String)getAddCatAttributeValue(key))) {
                        errors.add(key, new ActionError("error.category.globalattribute.violation", attr.getName()));
                    }
                }

                // check, if any dyna attribute name must not be empty
                List dynaAttrList = getDynaAttributes();
                
                for (int i = 0; i < dynaAttrList.size(); i++) {
                    LabelValueBean dynaAttr = (LabelValueBean)dynaAttrList.get(i);
                    
                    if (isEmpty(dynaAttr.getLabel())) {
                        errors.add("dynaAttributeLabel_" + i, new ActionError("error.category.dynaattribute.name", String.valueOf(i + 1)));
                    }
                }
			}
        } catch (DBException e) {
            VKCLogManager.errorLog(this, "", e.getMessage(),e);
        }

        return errors;
    }

	public HashMap getAddCatAttributes() {
		return addCatAttributes;
	}

	public void setAddCatAttributes(HashMap m) {
		addCatAttributes = m;
	}

	public Object getAddCatAttributeValue(String key) {
		return getAddCatAttributes().get(key);
	}

	public void setAddCatAttributeValue(String key, Object value) {		
	    getAddCatAttributes().put(key, value);
	}

	public Set getAddCatAttributeKeys() {
		return getAddCatAttributes().keySet();
	}
	
	public boolean getAddCatAttributeAllowNull(String key) throws DBException {
	    if (!isEmpty(key)) {
	        if (getAllAddCatAttributes().containsKey(key)) {
	            Integer allowNull = ((VKCAddAttribute)getAllAddCatAttributes().get(key)).getAllowNull();
	            
	            if (allowNull != null && allowNull.intValue() == 0) {
	                return false;
	            }
	        }
	    }
	    
	    return true;
	}

	public String getAddCatAttributeName(String key) throws DBException {
	    if (!isEmpty(key)) {
	        if (getAllAddCatAttributes().containsKey(key)) {
	            return ((VKCAddAttribute)getAllAddCatAttributes().get(key)).getName();
	        }
	    }
	    
	    return key;
	}

	public HashMap getAllAddCatAttributes() throws DBException {
		if (allAddCatAttributes == null) {
			allAddCatAttributes = new HashMap();
		    Vector addCatAttr = VKCAddAttributeSerializer.getAllAddCatAttributes();
	        
			for (int i = 0; i < addCatAttr.size(); i++) {
				VKCAddAttribute addAttribute = (VKCAddAttribute)addCatAttr.get(i);
				allAddCatAttributes.put("addcatattrId_" + addAttribute.getAttrId(), addAttribute);
			}
		}
		
	    return allAddCatAttributes;
	}
    
    public List getDynaAttributes() {
        return dynaAttributes;
    }

    public void setDynaAttributes(List list) {
        dynaAttributes = list;
    }

    private void synchronizeDynaAttributes(HttpServletRequest request) {
        getDynaAttributes().clear();
        int i=0;

        while (request.getParameter("dynaAttributeLabel_" + i) != null)  {
            String name  = StringUtils.normalize(request.getParameter("dynaAttributeLabel_" + i));
            String value = StringUtils.normalize(request.getParameter("dynaAttributeValue_" + i));
            getDynaAttributes().add(new LabelValueBean(name, value));
            i++;
        }
    }

    public String getDescription() {
        return description;
    }

	public String getEditMode() {
	    return editMode;
	}
	
    public String getKeywords() {
        return keywords;
    }

    public String getName() {
        return name;
    }

    public void setDescription(String s) {
        description = StringUtils.normalize(s);
    }

	public void setEditMode(String s) {
		editMode = StringUtils.normalize(s);
	}

    public void setKeywords(String s) {
        keywords = StringUtils.normalize(s);
    }

    public void setName(String s) {
        name = StringUtils.normalize(s);
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer integer) {
        categoryId = integer;
    }

	public VKCCategory getCategory() throws DBException {
		if (category == null) {
			category = VKCCategorySerializer.retrieveCategory(getCategoryId());
		}

		return category;
	}

    public String getExternalContacts() {
		return externalContacts;
	}

	public void setExternalContacts(String s) {
		externalContacts = StringUtils.normalize(s);
	}
	
	public String getSearchQuery() {
		return searchQuery;
	}

	public void setSearchQuery(String s) {
		searchQuery = StringUtils.normalize(s);
	}

	public Integer getSourcePageId() {
		return sourcePageId;
	}

	public void setSourcePageId(Integer i) {
		sourcePageId = i;
	}

	public VKCSearchQuery getQuery() {
		return query;
	}

	public void setQuery(VKCSearchQuery q) {
		query = q;
	}

	public String getLocalizedSearchQuery() throws DBException {
		VKCSearchQuery query = new VKCSearchQuery();
		query.setQuery(getSearchQuery());
		
		return query.getLocalizedHTMLString(getResources(), getLocale(), true, true);
	}

	public boolean isEmptyQuery() {
		VKCSearchQuery query = new VKCSearchQuery();
		query.setQuery(getSearchQuery());

		return query.isEmpty();
	}

	public Integer getSubTargetId() {
		return subTargetId;
	}

	public Integer getTargetId() {
		return targetId;
	}

	public void setSubTargetId(Integer i) {
		subTargetId = i;
	}

	public void setTargetId(Integer i) {
		targetId = i;
	}

    public Integer getSelectedIndex() {
        return selectedIndex;
    }

    public void setSelectedIndex(Integer i) {
        selectedIndex = i;
    }

    public boolean isHasPermissionForSearchQueries() {
    	return getUser().hasAdminPrivileges() || getUser().isManageVirtualDocumentQueries();
    }
}