/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlpackage;

/**
 *
 * @author Student
 */
import database.CoreDatabase;
import javax.microedition.midlet.*;
import java.io.*;
import java.util.Vector;
import org.kxml.parser.*;
import org.kxml.*;
import structures.SuperNodeObject;

/**
 * A simple app to demonstrate pull parsing using kXML.  It opens
 * a file from the resource directory /res then passes the InputStream
 * to a kXML parser.  The application will then ask the parser for the
 * next event.  If the start tag of an <address> element is
 * encountered then control is passed to the parseAddress function
 * which will begin retrieving data and continue doing so until
 * an end tag for </address> is encountered.
 *
 * This demonstrates how easy it is to use a pull parser by
 * fragmenting node parsing between functions.
 *
 * @author Robert Cadena
 */
public class NeighborsSuperNodeReaderNew {

    /**
     * Name of resource file we'll use later
     */
    public static String resfile_name;

    public NeighborsSuperNodeReaderNew(String file) {

        resfile_name = file;
    }

    /**
     * Creates an XML parser and parses a file in the local store looking
     * for address tags.  When it encounters such a tag it passes the
     * parser to another function.  If the end of document is reached
     * it exits.
     */
    public void beginParse() {
        XmlParser parser = null;
        java.lang.System.out.println(resfile_name);

        try {
            // create the parser and pass it the input stream for a file
            // Here you could also pass it an HTTP input stream
            parser = new XmlParser(new InputStreamReader(this.getClass().getResourceAsStream(resfile_name)), 300);


            // this is the event object we'll use to test against
            ParseEvent event = null;

            // now begin parsing the address and read until we get the
            // END_DOCUMENT event.
            while ((event = parser.read()).getType() != Xml.END_DOCUMENT) {


                // If it's a start tag, then test to see what kind it is
                if (event.getType() == Xml.START_TAG) {

                    // get the name and find out if it's "address"
                    String name = event.getName();
                    if (name != null && name.equals("superNode")) {
                        // Print notification to System.err
                        System.out.println("--[ SUPERNODE ]-----------");

                        // it is an address tag, so pass the parser over
                        // to the function that will parse the address
                        parseAddressTag(parser);

                        // Print end notification to System.err
                        System.err.println("------------------------\n");
                    }

                    name = null;
                }

                event = null;
            }


        } catch (IOException ioe) {
            // report error
            System.err.println("XML Parsing Error: " + ioe);
            ioe.printStackTrace();
        } finally {
            // try to close, and ignore any exceptions
            try {
                parser = null;
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * Parses the portion of the document between <address> tags.  Once
     * the end of that tag is reached control is returned to the calling
     * function.
     *
     * @throws IOException Exception thrown by XmlParser
     */
    public void parseAddressTag(XmlParser parser) throws IOException {
        ParseEvent event = null;
        Vector v = new Vector();

        // Instead of actually reading the next event we "peek" for the
        // next event.  It basically returns the next event but doesn't
        // move the parser ahead towards the next event.
        while ((event = parser.peek()).getType() != Xml.END_DOCUMENT) {

            // we'll use these later
            String name = event.getName();
            int type = event.getType();

            // test to see if it's the end tag of an address tag
            // and then return control to calling function
            if (type == Xml.END_TAG && name.equals("superNode")) {
                event = null;
                name = null;

                SuperNodeObject tmp = new SuperNodeObject();
                tmp.setID(v.elementAt(0).toString());
                tmp.setIPAddress(v.elementAt(1).toString());
                tmp.setRM_Tcp_portNo(v.elementAt(2).toString());
                tmp.setNode_tcp_portNo(v.elementAt(3).toString());
                tmp.setSuperNode_TCP_portNo(v.elementAt(4).toString());
                CoreDatabase.superNodes.addElement(tmp);
                return;
            }

            // now we read the event
            event = parser.read();

            // if it's not a start tag, then continue
            if (type != Xml.START_TAG) {
                // help out gc
                event = null;
                continue;
            }

            // if we know it's a start tag, then we skip forward one event
            // and read the TEXT between that tag
            ParseEvent next = parser.read();

            // if it's not a text event then skip it
            if (next.getType() != Xml.TEXT) {
                event = null;
                next = null;
                continue;
            }

            // now we get the text between those tags
            String text = next.getText();

            // and finally we print it out
            System.err.println(name + ": " + text);
            v.addElement(text);

            event = null;
            text = null;
            next = null;

        }
    }

    /**
     * Starts the parser
     *
     * @see javax.microedition.midlet.MIDlet#startApp()
     */
    protected void startApp() throws MIDletStateChangeException {
        beginParse();
    }

    /**
     * @see javax.microedition.midlet.MIDlet#destroyApp(boolean)
     */
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
    }

    /**
     * @see javax.microedition.midlet.MIDlet#pauseApp()
     */
    protected void pauseApp() {
    }
}
