package pt.link.utils.format;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;


public class FormattingUtils_XML extends FormElementUtils {
	private static Map instancesMap = new HashMap();
	
	public void init() throws FormattingException{
//		UtilProperties.getPropertyValue(resourceName,
//		"authorization.messageCode.request");
		
		InputStream inputStream =  this.getClass().getResourceAsStream(resourceName);
		if(inputStream == null)
			throw new FormattingException("null");//TODO arranjar isto
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
			
			for(Iterator it = properties.keySet().iterator();it.hasNext();){
				String propertyName = (String) it.next();
				if(propertyName.endsWith(".name")){
					int index = propertyName.indexOf(".");
					String elementName = propertyName.substring(0, index);
					FormElementMetaData elementMetaData = new FormElementMetaData();
					elementMetaData.name = elementName;
					elementMetaData.format = properties.getProperty(elementName + ".format");
					elementMetaData.type = properties.getProperty(elementName + ".type");
					elements.put(elementName, elementMetaData);
				}
				else
					continue;
			}
		} catch (IOException e) {
			log.error(e);
			throw new FormattingException("Unable to initialize FormElementUtils");
		}
//		FormElementMetaData obj = (FormElementMetaData) unmarshaller.unmarshall(FormElementMetaData.class, node);
//		obj.name = node.getNodeName();
//		elements.put(obj.name, obj);
	}
	
	private FormattingUtils_XML(String resourceName){
		super(resourceName);
	}
	
	public static FormElementUtils getInstance(String xmlResourceName) throws FormattingException{
		FormElementUtils oldInstance = (FormattingUtils_XML) instancesMap.get(xmlResourceName);
		if(oldInstance == null){
			FormattingUtils_XML newInstance = new FormattingUtils_XML(xmlResourceName);
			newInstance.init();
			instancesMap.put(xmlResourceName, newInstance);
			return newInstance;
		}
		return oldInstance;
	}
	
	public static void main(String args[]){
		FormElementUtils utils;
		try {
			utils = FormattingUtils_XML.getInstance("/sales.csv.properties");
			FormElementMetaData metaData = utils.getElement("PID");
			System.out.println("name: " + metaData.name);
			System.out.println("type: " + metaData.type);
			System.out.println("format: " + metaData.format);
			
			metaData = utils.getElement("SV");
			System.out.println("name: " + metaData.name);
			System.out.println("type: " + metaData.type);
			System.out.println("format: " + metaData.format);
			
		} catch (FormattingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
}
