//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.autoquest.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;
		
	}
}
