package dfatool.io;

import java.util.HashMap;
import java.util.Map;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

import dfatool.strategy.elements.Datatype;

public class DatatypeIOXML extends ElementIOXML<Datatype> implements IDatatypeIO{
	
	public final static String DATATYPE = "datatype";
	public final static String NAME = "name";
	public final static String EXPRESSION = "expression";
	
	public DatatypeIOXML(String filename){
		super(filename);
	}

	@Override
	protected void writeElements(XMLStreamWriter writer) throws XMLStreamException {
		for(Datatype at : map.values()){
			System.out.println(at.getName());
			writer.writeStartElement(DATATYPE);
			writer.writeAttribute(NAME, at.getName());
			writer.writeStartElement(EXPRESSION);
			writer.writeCharacters(at.getType());
			writer.writeEndElement();
			writer.writeEndElement();
		}
		
	}

	@Override
	protected Map<String, Datatype> readElements(XMLStreamReader reader) throws XMLStreamException {
		String name = null;
		String expression = null;
		Map<String, Datatype> map = new HashMap<String,Datatype>();
		skipToNextStartElement(reader);
		skipToNextStartElement(reader);
		while(reader.hasNext()){
			name = reader.getAttributeValue(0);
			skipToNextStartElement(reader);
			System.out.println(reader.getLocalName());
			if (reader.getLocalName().equals(EXPRESSION)) 
				expression = readText(reader);
			Datatype at = new Datatype(name, expression);
			map.put(at.getName(), at);
			skipToNextStartElement(reader);
		}
		return map;
	}


	public static void main(String[] args) {
		HashMap<String, Datatype> map = new HashMap<String,Datatype>();
		Datatype a1 = new Datatype("DT1", "{a,b,c,d}");
		Datatype a2 = new Datatype("DT2","{a,b,f,g}");
		Datatype a3 = new Datatype("DT3","{a,b,h,j}");
		map.put(a1.getName(), a1);
		map.put(a2.getName(), a2);
		map.put(a3.getName(), a3);
		DatatypeIOXML io = null;
		io = new DatatypeIOXML("types.xml");
		io.updateElement(a1);
//		io.updateElement(a2);
		io.updateElement(a3);
//		io.writeToFile();
//		io.readFromFile();
		System.out.println("Here");
		for(Datatype at: io.listElements()){
			System.out.println(at);
		}
	}
}
