package seng302.DataInput;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by fwy13 on 26/03/2017.
 */
public abstract class XMLReader {

    protected Document doc;

    /**
     * Read in XML file
     * @param filePath filepath for XML file
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public XMLReader(String filePath) throws ParserConfigurationException, IOException, SAXException {
        InputStream fXmlFile = getClass().getClassLoader().getResourceAsStream(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
    }

    /**
     * Return Document data of the read-in XML
     * @return XML document
     */
    public Document getDocument() {
        return doc;
    }

    /**
     * Get content of a tag in an element
     * @param n Element to read tags from
     * @param tagName Name of the tag
     * @return Content of the tag
     */
    public String getTextValueOfNode(Element n, String tagName) {
        return n.getElementsByTagName(tagName).item(0).getTextContent();
    }

    /**
     * Get attributes for an element
     * @param n Element to read attributes from
     * @param attr Attributes of element
     * @return Attributes of element
     */
    public String getAttribute(Element n, String attr) {
        return n.getAttribute(attr);
    }

}
