package seng302;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
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;

    protected 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();
    }

    protected XMLReader(InputStream xmlInput) throws ParserConfigurationException, IOException, SAXException {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(xmlInput);
    }

    public Document getDocument() {
        return doc;
    }

    protected String getTextValueOfNode(Element n, String tagName) {
        return n.getElementsByTagName(tagName).item(0).getTextContent();
    }

    protected boolean exists(Node node, String attribute) {
        return node.getAttributes().getNamedItem(attribute) != null;
    }

    public String getAttribute(Element n, String attr) {
        return n.getAttribute(attr);
    }

}
