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.NetworkElement;

public class NetworkIOXML extends ElementIOXML<NetworkElement> implements INetworkIO{
	
	public final static String ELEMENT = "elements";
	public final static String NAME = "name";
	public final static String EXPRESSION = "expression";
	
	public NetworkIOXML(String filename){
		super(filename);
	}

	@Override
	protected void writeElements(XMLStreamWriter writer) throws XMLStreamException {
		for(NetworkElement ne : map.values()){
			writer.writeStartElement(ELEMENT);
			writer.writeAttribute(NAME, ne.getName());
			writer.writeStartElement(EXPRESSION);
			writer.writeCharacters(ne.getExpression());
			writer.writeEndElement();
			writer.writeEndElement();
		}
		
	}

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


	public static void main(String[] args) {
//		HashMap<String, Channel> map = new HashMap<String,Channel>();
//		Channel a1 = new Channel("CH1", "{a,b,c,d}");
//		Channel a2 = new Channel("CH2","{a,b,f,g}");
//		Channel a3 = new Channel("CH3","{a,b,h,j}");
//		map.put(a1.getName(), a1);
//		map.put(a2.getName(), a2);
//		map.put(a3.getName(), a3);
//		NetworkIOXML io = null;
//		io = new NetworkIOXML("channels.xml");
//		io.updateElement(a1);
////		io.updateElement(a2);
//		io.updateElement(a3);
////		io.writeToFile();
////		io.readFromFile();
//		System.out.prHashMap<String, Channel> map = new HashMap<String,Channel>();
//		Channel a1 = new Channel("CH1", "{a,b,c,d}");
//		Channel a2 = new Channel("CH2","{a,b,f,g}");
//		Channel a3 = new Channel("CH3","{a,b,h,j}");
//		map.put(a1.getName(), a1);
//		map.put(a2.getName(), a2);
//		map.put(a3.getName(), a3);
//		NetworkIOXML io = null;
//		io = new NetworkIOXML("channels.xml");
//		io.updateElement(a1);
////		io.updateElement(a2);
//		io.updateElement(a3);
////		io.writeToFile();
////		io.readFromFile();
//		System.out.println("Here");
//		for(Channel at: io.listElements()){
//			System.out.println(at);
//		}intln("Here");
//		for(Channel at: io.listElements()){
//			System.out.println(at);
//		}
	}
}
