/*
 * XMLParser.fx
 *
 * Created on 9 Jun, 2009, 6:39:46 PM
 */

package placelist;

import java.io.InputStream;
import javafx.data.pull.Event;
import javafx.data.pull.PullParser;

/**
 @author Rakesh Menon
 */

public class XMLParser {

    var places : Place[];
    var place : Place;
    
    // Completion callback that also delivers parsed data
    public var onDone: function(places : Place[]) null;

    public function parse(input: InputStream) {
        
        // Parse the input data (Photo Metadata) and construct Photo instance
        def parser = PullParser {

            input: input
            
            onEvent: function(event: Event) {
                
                if(event.type == PullParser.TEXT) {
                    if(event.level == 4) {
                        if(event.qname.name == "place") {
                            if(place != null) {
                                insert place into places;
                            }
                            place = Place { };
                        }
                    else if(event.level == 5) {
                        if(event.qname.name == "woeId") {
                            place.woeId = event.text;
                        else if(event.qname.name == "type") {
                            place.type = event.text;
                        else if(event.qname.name == "latitude") {
                            place.latitude = event.text;
                        else if(event.qname.name == "longitude") {
                            place.longitude = event.text;
                        }
                    }
                else if(event.type == PullParser.CDATA) {
                    if(event.level == 5) {
                        if(event.qname.name == "name") {
                            place.name = event.text;
                        }
                    }
                else if (event.type == PullParser.START_DOCUMENT) {
                    delete places;
                    place = null;
                else if (event.type == PullParser.END_DOCUMENT) {
                    if(place != null) {
                        insert place into places;
                    }
                    if (onDone != null) { onDone(places)}
                }
            }
        };
        parser.parse();
    }
}