/*
 * $Id: XmlCategoryUtils.java,v 1.2 2004/11/09 16:08:01 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 */

package vkc.xml;

import java.util.Iterator;
import java.util.Set;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCKeyword;
import vkc.util.StringUtils;

public final class XmlCategoryUtils {
	private XmlCategoryUtils() {
	}
	
	/**
	 * Method inserts document meta information for the argument document
	 * into the "content"-Element of the XML document object
	 */
	public static final void addCategoryMetaData( Document xmlDoc, VKCCategory category ) {
		if ( xmlDoc == null || category == null ) {
			return;
		}
															  	
		Node contentNode = XmlUtils.getNodeByName( xmlDoc.getDocumentElement(), "content" );
		
		if ( contentNode == null ) {
			return;
		}

		Element root = createCategoryElement( xmlDoc, category );
		contentNode.appendChild( root );

		populateCategoryMetaElement( root, category );
	}

	// #########################################################################
	// # helper methods                                                        #
	// #########################################################################

	private final static Element createCategoryElement( Document xmlDoc, VKCCategory category ) {
		// Wurzelknoten erzeugen
		Element elem = xmlDoc.createElement( "category" );
		elem.setAttribute( "id", "" + category.getCategoryId() );
		
		return elem;
	}
	
	private final static void populateCategoryMetaElement( Element elem, VKCCategory category ) {
		Document owner = elem.getOwnerDocument();
		
		// Name einfügen
		Element name = owner.createElement( "categoryName" );
		name.appendChild( owner.createTextNode( StringUtils.normalize( category.getName() ) ) );
		elem.appendChild( name );

		// Beschreibung einfügen
		Element description = owner.createElement( "categoryDescription" );
		description.appendChild( owner.createTextNode( StringUtils.normalize( category.getDescription() ) ) );
		elem.appendChild( description );	

		// Keywords einfügen
		Set keywords = category.getKeywords();
		if ( keywords != null && !keywords.isEmpty() ) {
			for( Iterator iter = keywords.iterator() ; iter.hasNext() ; ) {
				VKCKeyword keyword = (VKCKeyword)iter.next();

				if ( keyword.isInternal() || StringUtils.isEmpty( keyword.getTerm() ) ) {
					continue;
				}

				Element keywordElem = owner.createElement( "keyword" );
				keywordElem.setAttribute( "name", keyword.getTerm().trim() );
				elem.appendChild( keywordElem );	
			}
		}
		
		// Erstellungsdatum einfügen
		if ( category.getCreated() != null ) {
			// Erstellungsdatum einfügen
			Element docPublished = owner.createElement( "created" );
			docPublished.setAttribute( "timestamp", "" + category.getCreated().getTime() );
			elem.appendChild( docPublished );
		}
	}
}