package fable.framework.writer;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import org.jdom.*;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import fable.framework.xmlparser.object.Xmloption;


/**
 * 
 * @author SUCHET
 * this class is used to write an xml document as ini file for imageD11 viewer. 
 * 
 */
/*<?xml version="1.0" encoding="UTF-8"?>
<root>
  <option name="stem">
    <value>test</value>
    <action>store</action>
    <type>string</type>
    <required>True</required>
    <short_name>n</short_name>
    <dest>stem</dest>
    <help>Name of the files up the digits part  eg mydata in mydata0000.edf</help>
  </option>
 (...)
</root>
*/
public class Xmlwriter {

	static Element root;
	private XMLOutputter xmlFile;
	private org.jdom.Document document;
	private Vector<Xmloption> myoptions;
	private  String elementName = "";
	
	public Xmlwriter(String rootName, String ElementName, String fileName,Vector<Xmloption> v_options) throws XmlwriterException{
		
		root= new Element(rootName); //"root"
		document = new Document(root);
		myoptions=v_options;
		elementName = ElementName;
		
		write();
	
		xmlFile = new XMLOutputter(Format.getPrettyFormat());
		
		try {
			xmlFile.output(document, new FileOutputStream(fileName));
			
			//xmlFile.output(document, System.out);
		} catch (FileNotFoundException e) {
			throw new XmlwriterException(0, this.getClass().getName(),"xmlWriter",e.getMessage());
		} catch (IOException e) {
			throw new XmlwriterException(0, this.getClass().getName(),"xmlWriter",e.getMessage());
		}
	}
	
	/**
	 * for each option, build 
	 *  
	 *  <option name="stem">
    	<value>test</value>
    	<action>store</action>
    	<type>string</type>
    	<required>True</required>
    	<short_name>n</short_name>
    	<dest>stem</dest>
    	<help>Name of the files up the digits part  eg mydata in mydata0000.edf</help>
  	</option>
	 */
	@SuppressWarnings("unchecked")
	private  void write(){
		for(int it=0; it<myoptions.size();it++){
			
			Xmloption xmloption=myoptions.elementAt(it);
			
			Element element = new Element(elementName);
			root.addContent(element);
			
			Attribute option = new Attribute("name", xmloption.getOption());
			element.setAttribute(option);
			
			Set<?> mySet = xmloption.getNode().entrySet ( ) ;
			Iterator<?> iterateAttributes = mySet.iterator ( ) ;
			while ( iterateAttributes.hasNext ( ) ) {

				Map.Entry entry = ( Map.Entry ) iterateAttributes.next ( ) ;
				if(!((String) entry.getKey()).equals("option")){
					
					Element attribut = new Element ( (String) entry.getKey());
					attribut.setText((String)entry.getValue());
					element.addContent(attribut);
				}
			}
			
		
		}
		
	}
	
}
