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.Channel;
import dfatool.strategy.elements.Var;

public class VarIOXML extends ElementIOXML<Var> implements IVarIO{
	
	public final static String VAR = "var";
	public final static String NAME = "name";
	public final static String EXPRESSION = "expression";
	
	public VarIOXML(String filename){
		super(filename);
	}

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

	@Override
	protected Map<String, Var> readElements(XMLStreamReader reader) throws XMLStreamException {
		String name = null;
		String expression = null;
		Map<String, Var> map = new HashMap<String,Var>();
		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);
			Var at = new Var(name, expression);
			map.put(at.getName(), at);
			skipToNextStartElement(reader);
		}
		return map;
	}


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