/*
 * $Id: SearchResultEntry.java,v 1.38 2008/04/17 10:01:00 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: SearchResultEntry.java,v $
 * Revision 1.38  2008/04/17 10:01:00  marbobo
 * + Velocity-Templates angepasst
 *
 * Revision 1.37  2006/09/29 21:10:07  marbobo
 * + Sucheoptimiert
 *
 * Revision 1.36  2006/05/14 17:27:37  marbobo
 * + Indexierung des Beschreibungsfeld korrigiert
 *
 * Revision 1.35  2005/09/15 00:49:20  marbobo
 * + Cachen von Herausgeber
 *
 * Revision 1.34  2005/09/04 23:21:21  marbobo
 * +Suche nach Metadaten-Attribute (Erstellungsdatum) für Dokumente implementiert
 *
 * Revision 1.33  2005/08/08 12:10:01  marbobo
 * + VorgängerId wird nun Ordnungsgemäß gesetzt
 *
 * Revision 1.32  2005/03/21 20:24:00  marbobo
 * + DocSize auf Type Long umgestellt
 *
 * Revision 1.31  2005/03/15 10:58:36  marbobo
 * + NPE wegen Notizen beseitigt
 *
 * Revision 1.30  2005/03/14 19:19:01  marbobo
 * + Problem mit Anzeigen von WWW-Kopien beseitigt
 * + Anzeigen von letzter Bearbeiter und Zeitpunkt hinzugefügt
 *
 * Revision 1.29  2005/02/10 01:06:54  marbobo
 * + Suche nach Unicode-Texten
 *
 * Revision 1.28  2004/11/09 14:35:41  marbobo
 * + Umstellung von authorId auf publisherId
 * + Hinzufügen von AuthorName für Dokumente
 * + Nötwendige Änderungen betreffend AuthorName und PublisherId
 *
 * Revision 1.27  2004/10/26 23:28:34  marbobo
 * + Feld lastAccessorId für VKCDocument-Objekte füllen
 *
 * Revision 1.26  2004/10/18 18:07:16  marbobo
 * + Feld lastAccessed für VKCDocument-Objekte füllen
 *
 * Revision 1.25  2004/10/04 13:43:31  marbobo
 * + Zugriffsanzahl anzeigen
 *
 * Revision 1.24  2004/06/24 23:29:50  marbobo
 * Quellcode maintenance
 *
 * Revision 1.23  2004/06/14 14:38:46  marbobo
 * change method name to additionalDocumentFormats
 *
 * Revision 1.22  2004/06/09 16:16:56  marbobo
 * + Zusätzliche Dokumente anzeigen
 *
 * Revision 1.21  2004/04/26 10:56:44  marbobo
 * - Unnötige Index-Einträge und Methoden entfernt
 *
 * Revision 1.20  2004/04/23 13:27:37  jonyp
 * getDocumentTypeIcon: return icon if document is versioned
 *
 * Revision 1.19  2004/04/20 18:22:07  marbobo
 * + toVKCDocument()
 *
 * Revision 1.18  2004/04/16 14:19:53  jonyp
 * spell checking
 *
 * Revision 1.17  2004/04/16 13:47:20  marbobo
 * + Suche nach Dokumentklassen
 *
 * Revision 1.16  2004/04/06 23:01:39  koppy
 * NPE in setDocClassId behoben
 *
 * Revision 1.15  2004/03/29 22:47:17  marbobo
 * 2 Methoden in StringUtils umbenannt
 *
 * Revision 1.14  2004/03/28 20:18:20  marbobo
 * Suche nach Dokumentklassen nochmals gefixt
 *
 * Revision 1.13  2004/03/22 13:02:52  marbobo
 * NPE beseitigt
 *
 * Revision 1.12  2004/03/18 11:57:06  marbobo
 * Bei Suchergebnissen wird nun statt DocClassName DocClassId gesetzt
 *
 * Revision 1.11  2004/03/07 13:45:47  bigmac
 * Anpassungen an VKCDocumentTypeSerializer, VKCDocumentClassSerializer, VKCDocumentStatusSerializer
 *
 * Revision 1.10  2004/02/16 10:03:11  bigmac
 * +getPercent()
 * +getDocumentTypeIcon()
 *
 * Revision 1.9  2004/02/09 10:11:03  marbobo
 * Dokumentsuche um zusätzliche Felder erweitert
 *
 * Revision 1.8  2003/12/24 10:12:12  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.7  2003/10/08 14:50:49  marbobo
 * Umstellung von VKCDocument nach SearchResultEntry
 *
 * Revision 1.6  2003/09/10 07:19:15  lawern
 * Zusätzliche Felder für die Ergebnisliste eingebaut.
 *
 * Revision 1.5  2003/08/05 15:06:44  bigmac
 * +getDocument()
 *
 * Revision 1.4  2003/04/16 09:17:50  lawern
 * Das published-Feld wird jetzt als Date übergeben
 *
 * Revision 1.3  2003/04/16 07:25:29  lawern
 * einige Felder vergessen zu initialisieren
 *
 * Revision 1.2  2003/04/14 23:25:07  marbobo
 * - Serialisierung der Klasse
 * - Getter und Setter-Methoden für die Instanzvariablen
 *
 * Revision 1.1  2003/04/09 14:16:02  lawern
 * initiale Version
 *
 */
package vkc.search;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.struts.util.LabelValueBean;

import vkc.db.entities.VKCAddAttribute;
import vkc.db.entities.VKCDocument;
import vkc.db.serializer.VKCAddAttributeSerializer;
import vkc.db.serializer.VKCDocumentClassSerializer;
import vkc.db.serializer.VKCDocumentFormatSerializer;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCDocumentStatusSerializer;
import vkc.db.serializer.VKCDocumentTypeSerializer;
import vkc.db.serializer.VKCDynaAttributeSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.util.StringUtils;
import vkc.util.VKCStringUtils;

/**
 * Diese Klasse dient zur Auflistung der Suchergebnisse.
 *
 * @author lawern
 */
public final class SearchResultEntry implements Serializable {
    private float score;

	private Date expires;
    private Date published;
    private Date creationDate;

    private List addDocAttribute;

    private String authorName;
    private String categoryId;
    private String description;
    private String docClassId;
    private String docSize;
	private String docStatusId;
    private String docTypeName;
    private String documentId;
    private String dynaAttrsId;
    private String keywords;
    private String name;
    private String publisherId;
    private String publisherName = null;
    private String title;
	private String versionDescr;
    private String versionHigh;
    private String versionLow;
    private String versionNo;

    /**
     * Konstruktor
     */
    public SearchResultEntry(String documentId, String docTypeName, String name,
            				 Date published, Date expires, Date creationDate, String keywords, String title, 
            				 String description, String publisherId, String authorName, float score, 
            				 String docClassId, String docStatusId, String docSize, String versionHigh, 
            				 String versionLow, String versionNo, String versionDescr, String categoryId, 
            				 List addDocAttribute, String dynaAttrsId) {
        this.documentId = documentId;
        this.docTypeName = docTypeName;
        this.name = name;
        this.published = published;
		this.expires = expires;
		this.creationDate = creationDate;
        this.keywords = keywords;
        this.title = title;
        this.description = description;
        this.publisherId = publisherId;
        this.authorName = authorName;
        this.score = score;
        this.setDocClassId(docClassId);
		this.setDocStatusId(docStatusId);
        this.docSize = docSize;
        this.versionHigh = versionHigh;
        this.versionLow = versionLow;
        this.versionNo = versionNo;
        this.versionDescr = versionDescr;
        this.categoryId = categoryId;
        this.addDocAttribute = addDocAttribute;
        this.dynaAttrsId = dynaAttrsId;
    }

    public static SearchResultEntry toSearchResultEntry(Document document, float score) throws ParseException, DBException {
        String str = document.get("expires");

        Date expires = ((str != null) && (str.length() > 0))
            ? DateTools.stringToDate(document.get("expires")) : null;

        str = document.get("creationDate");

        Date creationDate = ((str != null) && (str.length() > 0))
            ? DateTools.stringToDate(document.get("creationDate"))
            : null;

        str = document.get("dynaAttrsId");

        String dynaAttrsId = ((str != null) && (str.length() > 0))
            ? str : null;

        //zusätliche SuchFelder ermitteln
        List addDocAttr = new ArrayList();
        List addDocAttributes = VKCAddAttributeSerializer.getAllAddDocAttributes();
        Iterator it = addDocAttributes.iterator();

        while (it.hasNext()) {
            VKCAddAttribute attr = (VKCAddAttribute) it.next();
            String fieldName = attr.getName();
            String fieldValue = document
                                    .get("adddocattrId_" +
                    attr.getAttrId());
            LabelValueBean l = new LabelValueBean(fieldName, fieldValue);
            addDocAttr.add(l);
        }

        return new SearchResultEntry(document.get("documentId"),
                document.get("docTypeName"),
                document.get("name"),
                DateTools.stringToDate(document.get("published")),
                expires, creationDate, document.get("keywords"),
                document.get("title"),
                document.get("description"),
                document.get("publisherId"),
                document.get("authorname"), score,
                document.get("docClassId"),
                document.get("docStatusId"),
                document.get("docSize"),
                document.get("versionHigh"),
                document.get("versionLow"),
                document.get("versionNo"),
                document.get("versionDescr"),
                document.get("categoryId"), addDocAttr, dynaAttrsId);
    }
    
    public void setDocumentId(String s) {
        documentId = s;
    }

    public String getDocumentId() {
        return documentId;
    }

    public void setDocTypeName(String s) {
        docTypeName = s;
    }

    public String getDocTypeName() {
        return docTypeName;
    }

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

    public String getName() {
        return name;
    }

    public void setPublished(Date d) {
        published = d;
    }

    public Date getPublished() {
        return published;
    }

	public void setExpires(Date d) {
		expires = d;
	}

	public Date getExpires() {
		return expires;
	}

	public void setCreationDate(Date d) {
		creationDate = d;
	}

	public Date getCreationDate() {
		return creationDate;
	}

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

    public String getKeywords() {
        return keywords;
    }

    public void setTitle(String s) {
        title = s;
    }

    public String getTitle() {
        return title;
    }

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

    public String getDescription() {
        return description;
    }

    public void setPublisherId(String s) {
        publisherId = s;
    }

    public String getPublisherId() {
        return publisherId;
    }

    public void setAuthorName(String s) {
        authorName = s;
    }

    public String getAuthorName() {
        return authorName;
    }

	public String getPublisherName() {
		try {
			if (publisherName == null) {
				publisherName = VKCUserSerializer.retrieveUserInfo(Integer.valueOf(getPublisherId())).getLastnameLabel();
			}
			
			return publisherName;
		} catch ( Exception e ) {
			return "";
		}
	}
	
    public void setScore(float f) {
        score = f;
    }

    public float getScore() {
        return score;
    }

    public String getCategoryId() {
        return categoryId;
    }

    public String getDocClassId() {
        return docClassId;
    }

	public String getDocStatusId() {
		return docStatusId;
	}

	public String getDocClassName() {
		return VKCDocumentClassSerializer.getDocumentClass(Integer.valueOf(getDocClassId())).getNameKey();
	}

	public String getDocStatusName() {
		return VKCDocumentStatusSerializer.getDocumentStatus(Integer.valueOf(getDocStatusId())).getDescriptionKey();
	}

    public String getDocSize() {
        return docSize;
    }

	public String getDynaAttrsId() {
		return dynaAttrsId;
	}

    public String getVersionHigh() {
        return versionHigh;
    }

    public String getVersionLow() {
        return versionLow;
    }

    public String getVersionNo() {
        return versionNo;
    }

	public String getVersionDescr() {
		return versionDescr;
	}

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public void setDocClassId(String dcid) {
        if (dcid != null && dcid.startsWith("classid")) {
        	dcid = dcid.substring("classid".length(), dcid.length());
        }
        
		Integer id = null;
		
		try {
			id = StringUtils.decodeToInteger(dcid);
			
			if (id == null) {
				id = new Integer(0);
			}
		} catch (NumberFormatException e) {
			id = new Integer(0);
		}
        
        docClassId = id.toString();
    }

	public void setDocStatusId(String dsid) {
		if (dsid != null && dsid.startsWith("statusid")) {
			dsid = dsid.substring("statusid".length(), dsid.length());
		}
        
		Integer id = null;
		
		try {
			id = StringUtils.decodeToInteger(dsid);
			
			if (id == null) {
				id = new Integer(0);
			}
		} catch (NumberFormatException e) {
			id = new Integer(0);
		}
        
		docStatusId = id.toString();
	}

    public void setDocSize(String s) {
        docSize = s;
    }

	public void setDynaAttrsId(String s) {
		dynaAttrsId = s;
	}

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

    public void setVersionLow(String s) {
        versionLow = s;
    }

    public void setVersionNo(String s) {
        versionNo = s;
    }

	public void setVersionDescr(String s) {
		versionDescr = s;
	}

    public VKCDocument getDocument() throws DBException {
        return VKCDocumentSerializer.retrieveDocument(new Integer(getDocumentId()));
    }

	public List getAddDocAttribute() {
		return addDocAttribute;
	}

	public void setAddDocAttribute(List l) {
		addDocAttribute = l;
	}
	
	public double getPercent() {
		return Math.round(getScore() * 10000) / 100.0;
	}

	public VKCDocument toVKCDocument() throws DBException {
		VKCDocument doc = new VKCDocument();

		doc.setDocumentId(Integer.valueOf(getDocumentId()));
		doc.setCategoryId(Integer.valueOf(getCategoryId()));
		doc.setPreDocId(VKCDocumentSerializer.getPredecessorVersionDocId(doc.getDocumentId()));
		doc.setDocumentType(VKCDocumentTypeSerializer.getDocumentTypeByExtension(getDocTypeName()));
		doc.setName(VKCStringUtils.filterUnicodeChars(getName() != null ? getName() : ""));
		doc.setAuthorName(VKCStringUtils.filterUnicodeChars(getAuthorName()));
		doc.setPublished(getPublished());
		doc.setExpires(getExpires());
		doc.setCreationDate(getCreationDate());
		doc.setKeywordsByString(VKCStringUtils.filterUnicodeChars(getKeywords()));
		doc.setTitle(VKCStringUtils.filterUnicodeChars(getTitle()));
		doc.setDescription(VKCDocumentSerializer.getDocumentDescription(Integer.valueOf(getDocumentId())));
		doc.setPublisherId(Integer.valueOf(getPublisherId()));
		doc.setDocumentClass(VKCDocumentClassSerializer.getDocumentClass(Integer.valueOf(getDocClassId())));
		doc.setStatus(Integer.valueOf(getDocStatusId()));
		doc.setDocSize(Long.valueOf(getDocSize()));
		doc.setAccessCount(VKCDocumentSerializer.getAccessCount(doc.getDocumentId()));
		Timestamp lastAccessed = VKCDocumentSerializer.getLastAccessed(doc.getDocumentId());
		doc.setLastAccessed(lastAccessed != null ? new Date(lastAccessed.getTime()) : null);
		doc.setLastAccessorId(VKCDocumentSerializer.getLastAccessorId(doc.getDocumentId()));
		Timestamp lastChanged = VKCDocumentSerializer.getLastChanged(doc.getDocumentId());
		doc.setLastChanged(lastChanged != null ? new Date(lastChanged.getTime()) : null);
		doc.setLastChangerId(VKCDocumentSerializer.getLastChangerId(doc.getDocumentId()));
		doc.setVersionHigh(Integer.valueOf(getVersionHigh()));
		doc.setVersionLow(Integer.valueOf(getVersionLow()));
		doc.setVersionNo(Integer.valueOf(getVersionNo()));
		doc.setVersionDescr(VKCStringUtils.filterUnicodeChars(getVersionDescr()));
		doc.setAdditionalDocumentFormats(VKCDocumentFormatSerializer.retrieveAdditionalDocumentFormats(doc.getDocumentId()));
		Vector addAttributes = new Vector();

		for (int i = 0; i < getAddDocAttribute().size(); i++) {
			LabelValueBean l = (LabelValueBean)getAddDocAttribute().get(i);
			VKCAddAttribute attr = new VKCAddAttribute();
			attr.setName(VKCStringUtils.filterUnicodeChars(l.getLabel()));
			attr.setValuestring(VKCStringUtils.filterUnicodeChars(l.getValue()));
			addAttributes.add(attr);
		}

		doc.setAddAttributes(addAttributes);

		if (getDynaAttrsId() != null) {
			doc.setDynaAttrsId(Integer.valueOf(getDynaAttrsId()));
			VKCDynaAttributeSerializer.retrieveDynaAttributes(doc);
		}

		return doc;
	}
	
	public VKCDocument getToVKCDocument() throws DBException {
		return toVKCDocument();
	}
}