package pt.link.utils.format;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import pt.link.utils.xml.CastorUnmarshaller;
import pt.link.utils.xml.IXMLUnmarshaller;



public class FormElementUtils{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8152954421623158234L;
	protected HashMap elements;
	static Log log = LogFactory.getLog(FormElementUtils.class);
	protected String resourceName;
	
	private void init() throws FormattingException{
		InputStream iStream = FormElementUtils.class.getResourceAsStream(resourceName);
		if(iStream==null)
			log.error(resourceName + " not found");
		InputSource is = new InputSource(iStream);
		try {
			  DocumentBuilder builder =
			       DocumentBuilderFactory.newInstance().newDocumentBuilder();
			  
			  Document doc = builder.parse(is);
			
			  NodeList nodes = doc.getElementsByTagName("elements").item(0).getChildNodes();
			  for(int i=0;i<nodes.getLength();i++){
				  Node node = (Node) nodes.item(i);
				  if(node==null)
					  log.error("Problem parsing " + resourceName);
				  else{
					  if(node.getNodeType() != Node.ELEMENT_NODE)
						  continue;
				  }
				  IXMLUnmarshaller unmarshaller = CastorUnmarshaller.getInstance();
				  FormElementMetaData obj = (FormElementMetaData) unmarshaller.unmarshall(FormElementMetaData.class, node);
				  obj.name = node.getNodeName();
				  elements.put(obj.name, obj);
			  }
		}
		catch (Exception e) {
			log.error(e);
			throw new FormattingException("Unable to initialize FormElementUtils");
		}
	}
	
	private static Map instancesMap = new HashMap();
		
	protected FormElementUtils(String resourceName){
		this.resourceName = resourceName;
		elements = new HashMap();
	}
	
	public static FormElementUtils getInstance(String xmlResourceName) throws FormattingException{
		FormElementUtils oldInstance = (FormElementUtils) instancesMap.get(xmlResourceName);
		if(oldInstance == null){
			FormElementUtils newInstance = new FormElementUtils(xmlResourceName);
			newInstance.init();
			instancesMap.put(xmlResourceName, newInstance);
			return newInstance;
		}
		return oldInstance;
	}

	public FormElementMetaData getElement(String propertyName) throws FormattingException{
		
		return (FormElementMetaData)elements.get(propertyName);
	}
	
	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append("[");
		
		buf.append("]");
		return buf.toString();
	}

}
