/*
 * $Id: EditDocumentForm.java,v 1.16 2007/03/01 15:02:56 korowa Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * $Log: EditDocumentForm.java,v $
 * Revision 1.16  2007/03/01 15:02:56  korowa
 * Beschreibungen zur Kategorien und Dokumenten und News werden jetzt in eigener Tabelle NOTES über VKCNoteSerializer gespeichert und sind nicht begrenzt an Zeichenanzahl
 *
 * Revision 1.15  2005/09/07 23:51:19  marbobo
 * + Bugfix
 *
 * Revision 1.14  2005/09/04 23:20:10  marbobo
 * + Neues Metadaten-Attribute (Erstellungsdatum) für Dokumente hinzugefügt
 *
 * Revision 1.13  2005/08/30 14:34:50  jonyp
 * fixes due to changes of STATUS_.../FLAG_... from int to Integer
 *
 * Revision 1.12  2005/08/17 13:53:54  marbobo
 * + autoName in autoTitle umbenannt
 *
 * Revision 1.11  2005/08/16 08:51:26  korowa
 * Ermöglicht Abschalten der Convertergenerierung von Namen, Schlüsselwörter und Beschreibung
 *
 * Revision 1.10  2004/11/12 00:20:30  marbobo
 * - Unnötige Import-Anweisungen entfernt
 *
 * Revision 1.9  2004/11/10 15:02:47  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.8  2004/11/09 14:35:36  marbobo
 * + Umstellung von authorId auf publisherId
 * + Hinzufügen von AuthorName für Dokumente
 * + Nötwendige Änderungen betreffend AuthorName und PublisherId
 *
 * Revision 1.7  2004/10/22 12:40:37  marbobo
 * + Verfallsdatum darf nicht den heutigen Datum haben
 *
 * Revision 1.6  2004/10/17 20:05:27  marbobo
 * + Globale Dokumentattribute überarbeitet
 * + Publikationszeitpunkt frei wählbar
 *
 * Revision 1.5  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.VKCDocument;
import vkc.db.serializer.VKCAddAttributeSerializer;
import vkc.db.serializer.VKCDocumentClassSerializer;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCDocumentStatusSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.util.DateUtils;
import vkc.util.DocumentUtils;
import vkc.util.StringUtils;
import vkc.view.PageId;
import vkc.view.WebShare;

/**
 * Bean zum editieren von Dokumenten, HTML-Verweisen und
 * Notizen mit Struts
 *
 * @author marbobo
 */
public class EditDocumentForm extends BasicActionForm {
	public final static int ACTION_EDIT_DOCUMENT 	= 0;
	public final static int ACTION_EDIT_LINK		= 1;
	public final static int ACTION_EDIT_NOTE		= 2;

	private boolean autoTitle			= true;
	private boolean autoDescription		= true;
	private boolean autoKeyword			= true;

	private HashMap addDocAttributes	= new HashMap();
	private HashMap	allAddDocAttributes	= null;

	private Integer documentClassId = null;
    private Integer documentId 		= null;
	private Integer documentStatus 	= 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  documentAuthorName  = "";
    private String  documentDescription = "";
    private String  documentKeywords 	= "";
    private String  documentTitle 		= "";
	private String  expirationDate 		= "";
	private String  publishingDate 		= "";
	private String  creationDate 		= "";
	private String  versionDescription 	= "";
	private String  versionLow 			= "";
	private String  versionHigh 		= "";
   	
    private VKCCategory documentCategory = null;

    private VKCDocument document = null;

    public void reset(ActionMapping mapping, HttpServletRequest request) {
        super.reset(mapping, request);
        
    	autoTitle			= false;
		autoDescription		= false;
		autoKeyword			= false;

		addDocAttributes	= new HashMap();
    	allAddDocAttributes	= null;

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

        
        dynaAttributes = new ArrayList();

        documentAuthorName  = "";
        documentDescription = "";
        documentKeywords 	= "";
        documentTitle 		= "";
    	expirationDate 		= "";
    	publishingDate 		= "";
    	creationDate 		= "";
    	versionDescription 	= "";
    	versionLow 			= "";
    	versionHigh 		= "";
       	
        documentCategory = null;

        document = null;
    }

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

        try {
            synchronizeDynaAttributes(request);
            setAutoTitle(request.getParameter("autoTitle") != null);
			setAutoDescription(request.getParameter("autoDescription") != null);
			setAutoKeyword(request.getParameter("autoKeyword") != null);

			if (request.getParameter("action.save") != null) {
                // maximal erlaubte Länge der Beschreibung checken
				/*
				 * Speichermechanismus für Beschreibung ist geändert worden =>
				 * keine Längebegrenzung für description
				 * 
				 * if (!isLengthValid(getDocumentDescription(),
				 * "document.description")) { errors.add("description", new
				 * ActionError("error.document.description.size",
				 * InputFieldConstraints.getMaxLength("document.description"))); }
				 */
                if (!isEmpty(getCreationDate())) {
                    if (!isParsableDate(getCreationDate())) {
                        errors.add("creationDate", new ActionError("error.creation.date"));
                    }
                }

                if (!isEmpty(getExpirationDate())) {
                    if (!isParsableDate(getExpirationDate())) {
                        errors.add("expirationDate", new ActionError("error.expiration.date"));
                    } else {
                        Date expDate = DateUtils.parseDate(getExpirationDate());
                        Date refDate = new Date(System.currentTimeMillis());

                        if (refDate.after(expDate)) {
                            errors.add("expirationDate", new ActionError("error.expiration.date.elapsed"));
                        }
                    }
                }

				if (getDocument().getFlag().intValue() == VKCDocument.FLAG_TOBEPUBLISHED.intValue()) {
	                if (!isEmpty(getPublishingDate())) {
						if (!isParsableDate(getPublishingDate())) {
							errors.add("publishingDate", new ActionError("error.publishing.date"));
						} else {
							Date pubDate = DateUtils.getMaximizedDayTime(DateUtils.parseDate(getPublishingDate()));
							Date refDate = DateUtils.getMaximizedDayTime(new Date());
	
							if (refDate.after(pubDate)) {
								errors.add("publishingDate", new ActionError("error.publishing.date.before.today"));
							}
						}
					}
				}

				if (isEmpty(getDocumentAuthorName())) {
				    setDocumentAuthorName(getUser().getFirstname() + " " + getUser().getLastname());
				}
				
               if (isEmpty(getDocumentTitle())) {
                    errors.add("title", new ActionError("error.document.title"));
                }

                if (!isEmpty(getVersionHigh())) {
                    if (!isParsableInteger(getVersionHigh())) {
                        errors.add("newDocumentVersionHigh", new ActionError("error.document.version.high"));
                    }
                }

                if (!isEmpty(getVersionLow())) {
                    if (!isParsableInteger(getVersionLow())) {
                        errors.add("newDocumentVersionLow", new ActionError("error.document.version.low"));
                    }
                }

                // check, if any global attribute must not be empty
                Iterator it = getAllAddDocAttributes().keySet().iterator();
                
                while (it.hasNext()) {
                    String key = (String)it.next();
                    VKCAddAttribute attr = (VKCAddAttribute)getAllAddDocAttributes().get(key);
                    
                    if (attr.getAllowNull().intValue() == 0 && isEmpty((String)getAddDocAttributeValue(key))) {
                        errors.add(key, new ActionError("error.document.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.document.dynaattribute.name", String.valueOf(i + 1)));
                    }
                }

            }
        } catch (Exception e) {
            VKCLogManager.errorLog(this, "", e.getMessage(), e);
            errors.add("error", new ActionError("error.general", e.getMessage()));
        }
        
        return errors;
    }

	public HashMap getAddDocAttributes() {
		return addDocAttributes;
	}

	public void setAddDocAttributes(HashMap m) {
		addDocAttributes = m;
	}

	public Object getAddDocAttributeValue(String key) {
		return getAddDocAttributes().get(key);
	}

	public void setAddDocAttributeValue(String key, Object value) {		
	    getAddDocAttributes().put(key, value);
	}

	public Set getAddDocAttributeKeys() {
		return getAddDocAttributes().keySet();
	}
	
	public boolean getAddDocAttributeAllowNull(String key) throws DBException {
	    if (!isEmpty(key)) {
	        if (getAllAddDocAttributes().containsKey(key)) {
	            Integer allowNull = ((VKCAddAttribute)getAllAddDocAttributes().get(key)).getAllowNull();
	            
	            if (allowNull != null && allowNull.intValue() == 0) {
	                return false;
	            }
	        }
	    }
	    
	    return true;
	}

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

	public HashMap getAllAddDocAttributes() throws DBException {
		if (allAddDocAttributes == null) {
			allAddDocAttributes = new HashMap();
		    Vector addDocAttr = VKCAddAttributeSerializer.getAllAddDocAttributes();
	        
			for (int i = 0; i < addDocAttr.size(); i++) {
				VKCAddAttribute addAttribute = (VKCAddAttribute)addDocAttr.get(i);
				allAddDocAttributes.put("adddocattrId_" + addAttribute.getAttrId(), addAttribute);
			}
		    
		}
		
	    return allAddDocAttributes;
	}
    
    public Integer getDocumentId() {
        return documentId;
    }

    public void setDocumentId(Integer i) {
        documentId = i;
        document = null;
        documentCategory = null;
    }

    public VKCDocument getDocument() throws DBException {
        if (document == null) {
            document = VKCDocumentSerializer.retrieveDocument(getDocumentId());
        }
        
        return document;
    }

    public VKCCategory getDocumentCategory() throws DBException {
        if (documentCategory == null && getDocument() != null) {
            List list = DocumentUtils.getDocumentVersions(getDocument().getDocumentId());
            
            for (Iterator iter = list.iterator() ; iter.hasNext() ;) {
                VKCDocument doc = (VKCDocument)iter.next();
                documentCategory = doc.getCategory();
                
                if (documentCategory != null) {
                    break;
                }
            }
        }
        
        return documentCategory;
    }

	public void setDocumentKeywords(String s) {
        documentKeywords = StringUtils.normalize(s);
	}

	public String getDocumentKeywords() {
        return documentKeywords;
	}

	public void setExpirationDate(String s) {
		expirationDate = StringUtils.normalize(s);
	}

	public String getExpirationDate() {
		return expirationDate;
	}

	public void setPublishingDate(String s) {
		publishingDate = StringUtils.normalize(s);
	}

	public String getPublishingDate() {
		return publishingDate;
	}

	public void setCreationDate(String s) {
		creationDate = StringUtils.normalize(s);
	}

	public String getCreationDate() {
		return creationDate;
	}

    public Date getPublishingDateObject() {
        if (!isEmpty(getPublishingDate()) && isParsableDate(getPublishingDate())) {
            Date now = DateUtils.getMinimizedDayTime(new Date(System.currentTimeMillis()));
            Date p = DateUtils.getMinimizedDayTime(DateUtils.parseDate(getPublishingDate()));
            
            if (!now.equals(p) && now.before(p)) {
                return DateUtils.getMinimizedDayTime(DateUtils.parseDate(getPublishingDate()));
            }
        } 

        return new Date(System.currentTimeMillis());
    }

	public boolean getPublishNow() {
        if (!isEmpty(getPublishingDate()) && isParsableDate(getPublishingDate())) {
            Date now = DateUtils.getMinimizedDayTime(new Date(System.currentTimeMillis()));
            Date p = DateUtils.getMinimizedDayTime(DateUtils.parseDate(getPublishingDate()));
            
            if (!now.equals(p) && now.before(p)) {
                return false;
            }
        } 

        return true;
	}
	
	public String getVersionHigh() {
		return versionHigh;
	}

	public void setVersionHigh(String s) {
		versionHigh = StringUtils.normalize(s);
	}

	public String getVersionLow() {
		return versionLow;
	}

	public void setVersionLow(String s) {
		this.versionLow = StringUtils.normalize(s);
	}

	public String getVersionDescription() {
		return versionDescription;
	}

	public void setVersionDescription(String s) {
		versionDescription = StringUtils.normalize(s);
	}

    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 Integer getDocumentStatus() {
		return documentStatus;
	}

	public void setDocumentStatus(Integer i) {
		documentStatus = i;
	}

    public List getDocumentStati() {
        return VKCDocumentStatusSerializer.getDocumentStati();
    }

    public List getDocumentClasses() {
        return VKCDocumentClassSerializer.getDocumentClasses();
    }

    public Integer getDocumentClassId() {
        return documentClassId;
    }

    public void setDocumentClassId(Integer i) {
        documentClassId = i;
    }

    public String getDocumentAuthorName() {
        return documentAuthorName;
    }

    public void setDocumentAuthorName(String s) {
        documentAuthorName = StringUtils.normalize(s);
    }

    public String getDocumentDescription() {
        return documentDescription;
    }

    public void setDocumentDescription(String s) {
        documentDescription = StringUtils.normalize(s);
    }

    public String getDocumentTitle() {
        return documentTitle;
    }

    public void setDocumentTitle(String s) {
        documentTitle = StringUtils.normalize(s);
    }
    
    public List getDynaAttributes() {
        return dynaAttributes;
    }

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

    public Integer getSelectedIndex() {
        return selectedIndex;
    }

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

	public Integer getSourcePageId() {
		return sourcePageId;
	}

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

	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 boolean isAutoDescription() {
        return autoDescription;
    }
    
	public void setAutoDescription(boolean autoDescription) {
        this.autoDescription = autoDescription;
    }
    
	public boolean isAutoKeyword() {
        return autoKeyword;
    }
    
	public void setAutoKeyword(boolean autoKeyword) {
        this.autoKeyword = autoKeyword;
    }
    
	public boolean isAutoTitle() {
        return autoTitle;
    }
    
	public void setAutoTitle(boolean autoTitle) {
        this.autoTitle = autoTitle;
    }
    
	public boolean isAdminAutoTitle()  {
	    if (Integer.parseInt(WebShare.getSysParameterValue("DOCUMENT", "EnableDocumentTitle", "1" ))  != 0) {
	        return true;
	    }
	    
	    return false;
	}
    
	public boolean isAdminAutoDescription()  {
	    if (Integer.parseInt(WebShare.getSysParameterValue("DOCUMENT", "EnableDocumentDescription", "1")) != 0)	{
	        return true;
	    }
	    
	    return false;
	}
	
    public boolean isAdminAutoKeyword()  {
	    if (Integer.parseInt(WebShare.getSysParameterValue("DOCUMENT", "EnableDocumentKeyword", "1")) != 0) {
	        return true;
	    }

	    return false;
	}
}