/*
 * Created on 9 juin 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.injac.oai.server.catalog.set;
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import java.util.ArrayList;


import org.apache.log4j.Logger;
import org.injac.oai.util.OAITags;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 * Class SetManager :
 * Manage setSpecs for webdav OAI repository
 * @author François Jannin june 2004
 *
 * 
 */
public class SetManager {
	/**
	 * Static logger
	 */
	static Logger logger = Logger.getLogger(SetManager.class);
	private File setFile;
	private ArrayList matchers;
	public SetManager(File setFile)
	{
		this.setFile = setFile;
		SetMatcherFactory setMatcherFactory = new SetMatcherFactory();
		// build matchers
		matchers = setMatcherFactory.createSetMatchers(setFile);
	}
	/**
	 * 
	 * @param nativeItem
	 * @return a list of string containig the value(s) of the OAI element(s) setSpec for an given item
	 */
	public ArrayList getSetSpecsFromItem(Object nativeItem){
		ArrayList setSpecs = new ArrayList();
		for(int i =0;i<matchers.size();i++)
		{
			SetMatcher matcher = (SetMatcher)matchers.get(i);
			String setSpec = matcher.getSetSpec(nativeItem);
			if(setSpec != null)
				setSpecs.add(setSpec);
		}
		return setSpecs;
	}
	/**
	 * Parse OAI sets from xml file
	 * @param setFile
	 * @return array of OAI set elements
	 */
	public String[] loadSetsFromFile(File setFile)
    {
		// Create DocumentBuilderFactory  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // Configure it to ignore comments
        //factory.setIgnoringComments(true);
        String [] setSpecs = new String[] {""};
        ArrayList setList = new ArrayList();
        Document doc;
        
		// Create the builder and doc
        try{
        	//   Load the specified XML document
        	DocumentBuilder builder = factory.newDocumentBuilder();
        	doc = builder.parse(setFile);
        	//setMatcher = setMatcher
        }catch(Exception e)
		{
        	logger.error("SetManager::loadSetsFromFile  "+e.getClass().getName()+" : "+e.getMessage());
        	return setSpecs;
		}
        // parse the file
		try {
        	//Element el =doc.getDocumentElement();
        	NodeList setNodes = doc.getElementsByTagName("set");
        	for(int nodeIndex = 0; nodeIndex < setNodes.getLength();nodeIndex++)
            {
                Node curResultNode = setNodes.item(nodeIndex);
            	Element el=(Element)curResultNode;
            	String tagName = el.getTagName();
            	logger.debug("Element :" + tagName);
            	String set="<"+tagName+">";
            	NodeList subelements = el.getChildNodes();
            	for(int i=0;i<subelements.getLength();i++)
            	{
            		try{
            			Element subel=(Element) subelements.item(i);
            			String subTag = subel.getTagName();
            			logger.debug("\n\tsub-element :" +subTag );
            			//  filter set elements
            			if("setSpecs setName setDescription".indexOf(subTag) != -1)
            			{	
            				set+="<"+subTag+">";
            				String value = subel.getFirstChild().getNodeValue();
            				if(subTag.equals("setDescription"))
            					set+=getDCDescriptionTagContent(value);
            				else
            					set+=value;
            				set+="</"+subTag+">";
            			}
            		}catch(ClassCastException ce)
					{
            				// nop, skipping
					}
            	}
            	
            	set+="</"+tagName+">";
            	logger.debug(set);
            	setList.add(set);
            	
            }	
        	Object[] objArray = setList.toArray();
        	// damned each element to cast one by one
        	setSpecs = new String[objArray.length];
        	for(int i=0;i<objArray.length;i++)
        		setSpecs[i]= (String)objArray[i];
        		
    	
		}catch(Exception e)
		{
			logger.error("SetManager::loadSetsFromFile  "+e.getClass().getName()+" : "+e.getMessage());
		}
		return setSpecs;
		
    	
    }
	private String getDCDescriptionTagContent(String value){
		return  OAITags.OAI_DC_OPEN_TAG+"<dc:description>"+value+"</dc:description>"+OAITags.OAI_DC_CLOSE_TAG;
	}

}
