package atmsdriver.model;

import atmsdriver.NetworkLoader;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author andrew
 */
public class Network {

    final private ArrayList<FEPLine> lines;
    final private HighwayStatusWriter hwyStatusWriter;

    public Network(File LDSFile, File loopFile, String hostName, int portNum) {
        lines = (ArrayList<FEPLine>) new NetworkLoader(LDSFile, loopFile).getFEPLines();
        hwyStatusWriter = new HighwayStatusWriter(hostName, portNum);
    }

    public void writeToFEP() {
        try {
            hwyStatusWriter.write(toXML());
        } catch (IOException ex) {
            Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String toXML() {
        String xml = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document theDoc = builder.newDocument();

            Element networkElement = theDoc.createElement(XML_TAGS.NETWORK.tag);
            theDoc.appendChild(networkElement);

            for (FEPLine line : lines) {
                line.toXML(networkElement);
            }

            Transformer tf = TransformerFactory.newInstance().newTransformer();

            tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            Writer out = new StringWriter();
            tf.transform(new DOMSource(theDoc), new StreamResult(out));
            xml = out.toString();
            out.close();
        } catch (Exception ex) {
            Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
        }
        return xml;

    }

    private static enum XML_TAGS {

        NETWORK("Network");

        String tag;

        private XML_TAGS(String n) {
            tag = n;
        }
    }
}
