package hibergui.generator.tool.xml;

import hibergui.HiberGUI;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

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

/**
 * Reads HiberGUI configuration (<code>hibergui-configuration</code>) file. 
 * Validate it by DTD file which is specified at <code>DOCTYPE</code> element of mapping XML
 * or if it is not available - file doesn't exist - then validate by DTD file
 * in <code>hibergui.jar</code> archive.
 * 
 * @author Csaba Gyenge
 *
 */
public class ConfigReader extends XMLReader {
	private static final String ROOT_NODE_NAME = "hibergui-configuration";
	private static final String MAPPING_NODE_NAME = "mapping";
	private static final String MAPPING_ATTRIBUTE_NAME = "resource";
	
	private static final String DTD_FOLDER = "dtd";
	private static final String DTD_FILE = "hibergui-configuration-1.0.dtd";
	
	public ConfigReader(String file) throws SAXException,
			IOException, ParserConfigurationException, TransformerException {
		super(new FileInputStream(new File(file)), HiberGUI.class.getResourceAsStream(DTD_FOLDER + "/" + DTD_FILE));
	}

	/**
	 * Get list of path of XML resource documents.
	 * 
	 * @return List of path of XML resource documents.
	 */
	public ArrayList<String> getMappingResources(){
		ArrayList<String> res = new ArrayList<String>();
		NodeList nl = getNode(Node.ELEMENT_NODE, this.getDOM().getNode(), ROOT_NODE_NAME, null).getChildNodes();
		for (int i = 0; i < nl.getLength(); i++){
			Node n = nl.item(i);
			if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(MAPPING_NODE_NAME)){
				res.add(n.getAttributes().getNamedItem(MAPPING_ATTRIBUTE_NAME).getNodeValue());
			}
		}
		return res;
	}
}
