/*
 * PacketXMLParser.java
 *
 * Autor: Piotr Achinger <piotr.achinger at gmail.com>
 */
package dendrarium.portal.admin;

import dendrarium.utils.XMLUtils;
import java.io.InputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * Parser plikow paczka.xml
 *
 * Aktualny format to
 *
 * <packet name="nazwa paczki">
 *  <forest file="plik_1.xml" />
 *  ...
 *  <forest file="plik_n.xml" />
 * </packet>
 *
 * @author Piotr Achinger <piotr.achinger at gmail.com>
 */
public class PacketXMLParser {

    private PacketXML packetXML;

    public PacketXML parse(InputStream is) throws Exception {
        Document doc = XMLUtils.parseXML(is);

        parsePacketElement(doc.getDocumentElement());

        return packetXML;
    }

    private void parsePacketElement(Element packetElement) {
        String name = packetElement.getAttribute("name");

        packetXML = new PacketXML(name);

        NodeList forestElements = packetElement.getElementsByTagName("forest");

        for (int i = 0 ; i < forestElements.getLength() ; ++i) {
            parseForestElement((Element) forestElements.item(i));
        }
    }

    private void parseForestElement(Element forestElement) {
        String filename = forestElement.getAttribute("file");

        packetXML.getForestFiles().add(filename);
    }
}
