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;

public class ChannelIOXML extends ElementIOXML<Channel> implements IChannelIO{
	
	public final static String CHANNEL = "channel";
	public final static String NAME = "name";
	public final static String TYPE = "type";
	
	public ChannelIOXML(String filename){
		super(filename);
	}

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

	@Override
	protected Map<String, Channel> readElements(XMLStreamReader reader) throws XMLStreamException {
		String name = null;
		String type = null;
		Map<String, Channel> map = new HashMap<String,Channel>();
		skipToNextStartElement(reader);
		skipToNextStartElement(reader);
		while(reader.hasNext()){
			name = reader.getAttributeValue(0);
			skipToNextStartElement(reader);
			System.out.println(reader.getLocalName());
			if (reader.getLocalName().equals(TYPE)) 
				type = readText(reader);
			Channel at = new Channel(name, type);
			map.put(at.getName(), at);
			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);
		ChannelIOXML io = null;
		io = new ChannelIOXML("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);
		}
	}
}
