package atmsdriver.network.model;

import atmsdriver.NetworkReader;
import java.io.File;
import java.io.FileWriter;
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.parsers.ParserConfigurationException;
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 File networkFile;
    
    public Network(File LDSFile, File loopFile, File networkFile)
    {
        lines = (ArrayList<FEPLine>) 
                new NetworkReader(LDSFile, loopFile).getFEPLines();
        this.networkFile = networkFile;
    }
    
    public void toXML() throws Exception
    {
        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));
            String xml = out.toString();
            out.close();
            
            Writer fileWr = new FileWriter(networkFile);
            fileWr.write(xml);
            fileWr.close();
            
            
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private static enum XML_TAGS
    {
        NETWORK("Network");
        
        String tag;
        
        private XML_TAGS(String n)
        {
            tag = n;
        }
    }
}
