package de.ugoe.cs.quest.plugin.jfc;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class JFCReplayIDValidator {
	private Set<String> validIds = null;
	
	public JFCReplayIDValidator(File guitarEfgFile) throws ParserConfigurationException, SAXException, IOException{
		this.initialize(guitarEfgFile);
	}
	
	public void initialize(File guitarGUIFile) throws ParserConfigurationException, SAXException, IOException{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document freemindGUI = builder.parse(guitarGUIFile);
	
		validIds = new HashSet<String>();
		
		NodeList guis = freemindGUI.getFirstChild().getChildNodes();
		for (int i = 0; i < guis.getLength(); i++)
			extractIDs(guis.item(i));
	}
	
	private void extractIDs(Node node){
		NodeList children = node.getChildNodes();
		if (children != null){
			for (int j = 0; j < children.getLength(); j++){
				if (children.item(j).getNodeName().equals("Attributes")){
					NodeList properties = children.item(j).getChildNodes();
					for (int i = 0; i < properties.getLength(); i++){
						NodeList property = properties.item(i).getChildNodes();
						for (int k = 0; k < property.getLength(); k++){
							if (property.item(k).getTextContent().equals("ID")){
								validIds.add(property.item(k+2).getTextContent());
							}
						}
					}
				}
				else{
					extractIDs(children.item(j));
				}
			}
		}
	}
	

	public boolean validateReplayID(String replayID){
		if (validIds == null || validIds.size() == 0)
			throw new IllegalStateException("There are no valid IDs known, call initialize first.");
		
		if (validIds.contains(replayID))
			return true;
		
		return false;
		
	}
}
