package de.renew.gui.pnml.parser;

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

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

import de.renew.draw.storables.ontology.Drawing;


/**
 * Use Singleton Patterm
 */
public class PNMLParser {
    private static final org.apache.log4j.Logger logger =
        org.apache.log4j.Logger.getLogger(PNMLParser.class);
    private static PNMLParser _instance;

    public static PNMLParser instance() {
        if (_instance == null) {
            _instance = new PNMLParser();
        }
        return _instance;
    }

    private PNMLParser() {}

    public List<Drawing> parse(InputStream pnmlStream) {
        List<Drawing> list = new ArrayList<>();
        try {
            // Erstellen des DOM Parsers
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Erstellen des DOM Baums
            Document doc = builder.parse(pnmlStream);

            NodeList nets = doc.getElementsByTagName("net");
            list = new ArrayList<>();
            for (int pos = 0; pos < nets.getLength(); pos++) {
                Element net = (Element) nets.item(pos);
                NetParser netParser = new NetParser(net);
                netParser.parse();
                list.add(netParser.getNet());
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            logger.error(e.getMessage(), e);
        }

        return list;
    }
}