/*
 * DeploymentXMLLoader.java
 *
 * Created on April 7, 2008, 3:17 PM
 */

package sidnet.models.deployment.models.xml;

import bsh.This;
import java.io.File;
import java.util.Iterator;
import javax.swing.filechooser.FileFilter;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import jist.runtime.JistAPI;
import sidnet.core.misc.NCS_Location2D;
import sidnet.core.misc.XMLUtils;
import jist.swans.field.Placement; 
import jist.swans.misc.Location;
import jist.swans.misc.Location.Location2D;
import sidnet.models.deployment.manager.DeploymentManager;

/**
 *
 * @author  Oliver
 */
public class DeploymentXMLLoader extends javax.swing.JFrame implements JistAPI.DoNotRewrite
{
    private List <NCS_Location2D> outputList = new LinkedList<NCS_Location2D>();
    private String filename = null;
    private Boolean compatibilityPassed = false; 
    private DeploymentManager callbackManager = null;
    private int fieldLength;
    private int fieldWidth;
  
    private final static String DEPLOYMENTXMLDIR = System.getenv("DEPLOYMENTXMLDIR");
    private final static String SIDNETDIR = System.getenv("SIDNET");

    /** Creates new form DeploymentXMLLoader */
    public DeploymentXMLLoader(DeploymentManager callbackManager, int fieldLength, int fieldWidth)
    {
        initComponents();
        this.fieldLength = fieldLength;
        this.fieldWidth = fieldWidth;
        
        this.callbackManager = callbackManager;
        if (DEPLOYMENTXMLDIR != null)
            jFileChooser1.setCurrentDirectory(new File(DEPLOYMENTXMLDIR));
        else
            if(SIDNETDIR != null)
                jFileChooser1.setCurrentDirectory(new File(SIDNETDIR));
       
        jFileChooser1.setFileFilter(new XMLFileFilter());
        jFileChooser1.showOpenDialog(this);       
    }
    
    
    class XMLFileFilter extends FileFilter
{
    public boolean accept(File filename)
    {
        if (filename.getName().endsWith(".xml"))
            return true;
        return false;
    }
    
    public String getDescription()
    {
        return "*.xml";
    }
}

    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        jFileChooser1 = new javax.swing.JFileChooser();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jFileChooser1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jFileChooser1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jFileChooser1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jFileChooser1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jFileChooser1ActionPerformed
    {//GEN-HEADEREND:event_jFileChooser1ActionPerformed
        // TODO add your handling code here:
        System.out.println(evt.getActionCommand());
        if(evt.getActionCommand()=="ApproveSelection"){
            compatibilityPassed = XMLUtils.xmlValidation(jFileChooser1.getSelectedFile());
            filename = ((File)jFileChooser1.getSelectedFile()).getName();
            this.dispose();
            Placement placement = parseXMLFile(((File)jFileChooser1.getSelectedFile()));
            callbackManager.jXMLLoaderCompletes(filename, compatibilityPassed, placement);
        }
        if(evt.getActionCommand()=="CancelSelection"){
            this.dispose();       
        }

    }//GEN-LAST:event_jFileChooser1ActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser jFileChooser1;
    // End of variables declaration//GEN-END:variables
    
    private Placement parseXMLFile(File xmlFilename)
    {
        LocationData locationData = (LocationData)XMLUtils.xmlParser("deployment", xmlFilename);
        return new XMLPlacement(locationData, fieldWidth, fieldLength);
    }
    
    
    class XMLPlacement implements Placement
    {
        private Iterator locationDataIterator;
        private int index = 0;
        private int size;
        private int fieldWidth;
        private int fieldLength;
        
        public XMLPlacement(LocationData locationData, int fieldLength, int fieldWidth)
        {
            this.locationDataIterator = (locationData.nodesList).iterator();
            this.size = locationData.nodesList.size();
            
            this.fieldLength = fieldLength;
            this.fieldWidth = fieldWidth;
        }
        
        public int getSize()
        {
            return size;
        }
        
         /**
           * Return location of next node.
           *
           * @return location of next node
           */
         public Location getNextLocation()
         {
             LocationData.Loc nextNode = null;
             if (locationDataIterator.hasNext())
                nextNode = (LocationData.Loc)locationDataIterator.next();
             if (nextNode != null)
                return new Location2D(nextNode.x * fieldWidth, nextNode.y * fieldLength);
             else
                return null;
         }
    }
    
    /*private List <NCS_Location2D> parseXMLFile(File filename)
    {
         List <NCS_Location2D> tempList = new LinkedList<NCS_Location2D>();
        try {
            
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (filename);

            // normalize text representation
            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " + 
                 doc.getDocumentElement().getNodeName());

            NodeList listOfNodes = doc.getElementsByTagName("node");
            int totalNodes = listOfNodes.getLength();
            System.out.println("Number of nodes : " + totalNodes);

            for(int s=0; s<listOfNodes.getLength() ; s++){
                Node firstNode = listOfNodes.item(s);
                if(firstNode.getNodeType() == Node.ELEMENT_NODE){
                    double tempx, tempy;
                    Element firstNodeElement = (Element)firstNode;
                    //-------
                    NodeList xNodeList = firstNodeElement.getElementsByTagName("x");
                    Element xNodeElement = (Element)xNodeList.item(0);
                    NodeList textXList = xNodeElement.getChildNodes();
                    tempx = Double.parseDouble(((Node)textXList.item(0)).getNodeValue().trim());
                    
                    //-------
                    NodeList yNodeList = firstNodeElement.getElementsByTagName("y");
                    Element yNodeElement = (Element)yNodeList.item(0);
                    NodeList textYList = yNodeElement.getChildNodes();
                    tempy = Double.parseDouble(((Node)textYList.item(0)).getNodeValue().trim());
                    
                    NCS_Location2D temp = new NCS_Location2D(tempx,tempy);
                    tempList.add(temp);
                }//end of if clause
            }//end of for loop with s var

            for(int i = 0; i <tempList.size(); i++)
            {
                System.out.println("X: " + tempList.get(i).getX() + "   Y: "
                                    + tempList.get(i).getY());
            }
        }
        catch (SAXParseException err) {
            System.out.println ("** Parsing error" + ", line " 
                + err.getLineNumber () + ", uri " + err.getSystemId ());
            System.out.println(" " + err.getMessage ());

        }
        catch (SAXException e) {
            Exception x = e.getException ();
            ((x == null) ? e : x).printStackTrace ();

        }
        catch (Throwable t) {
            t.printStackTrace ();
        }
        return tempList;
    }  */
}

@XmlRootElement(name="deployment")
    class LocationData implements JistAPI.DoNotRewrite
    {
        public LocationData()
        {
        }
        
        @XmlElement(name="node")
        public List<Loc> nodesList;
        
        public static class Loc
        {
            @XmlElement(name="x")
            Float x;
            
            @XmlElement(name="y")
            Float y;
        }
    }

