//FIXME: Add distinct logger for this file?

// Another hack, keep track of all features we have ever seen
// for 'pnum' lookup.  Should be replaced with a real call to 
// the server to really get them all so that we are not dependent
// on starting conditions to ensure we have 'seen them all'.
function AllFeaturesManager() {
    this._points = new Object();
}

AllFeaturesManager.prototype.getPoint = function(key) {
    if (key != null) {
        return this._points[key];
    }
}

AllFeaturesManager.prototype.getAllKeys = function() {
    var keys = new Array();
    for (var key in this._points) {
        keys.push(key);
    }
    return keys;
}

AllFeaturesManager.prototype.addPoint = function(key, point) {
    if (key != null) {
        // Let's hope javascript has good garbage collection
        this._points[key] = point;
    }
}

AllFeaturesManager.prototype.addPoints = function(keyAttr, points) {
    if (points != null) {
        for (var pKey in points) {
            var p = points[pKey];
            var pAttrKey = p.getAttribute(keyAttr);
            if (pAttrKey != null) {
                this.addPoint(pAttrKey, p);
            }
        }
    }
}

AllFeaturesManager.prototype.clearPoints = function() {
    this._points = new Object();
}

var allFeaturesManager = new AllFeaturesManager();


function FeatureManager(symbolFieldName) {
    this._symbolFieldName = symbolFieldName;
}

FeatureManager.prototype.getPoints = function() {
    return this._points;
}

FeatureManager.prototype.getPoint = function(pointID) {
    mapLog.debug("getPoint: (" + pointID + ")" + this._points[pointID]);
    return this._points[pointID];
}


FeatureManager.prototype.getPointByAttr = function(attrName, attrValue) {
    for (var pKey in this._points) {
        var p = this._points[pKey];
        var pValue = p.getAttribute(attrName);
        if (pValue == attrValue) {
            return p;
        }
    }
}

CSVFeatureManager.prototype = new FeatureManager();

function CSVFeatureManager(symbolFieldName) {
    FeatureManager.call(this,symbolFieldName);
}

CSVFeatureManager.prototype.processCSV = function(csvString) {
    if (csvString != null) {
        var featureList = csvString.split("\n");
        if (statistics) {
            // (Re)Initialize the global array of stats.
            symbolNameArray = new Object();
        }
        this._points = new Object();
        this._keys = new Object();
        
        if (featureList != null && featureList.length > 1) {
            var symbCol = -1;
            var latCol = -1;
            var lonCol = -1;
            var idCol = -1;
            this._keys = featureList[0].split(",");
            //mapLog.debug("processCSV: Processing csv header: " + featureList[0]);
            for (var i=0; i<this._keys.length; i++) {
                if (this._symbolFieldName.toLowerCase() == this._keys[i].toLowerCase()) {
                    symbCol = i;
                } else if ("lat" == this._keys[i].toLowerCase()) {
                    latCol = i;
                } else if ("lon" == this._keys[i].toLowerCase()) {
                    lonCol = i;
                } else if ("fid" == this._keys[i]) {
                    idCol = i;
                }
            }
            if (symbCol < 0 || latCol < 0 || lonCol < 0 || idCol < 0) {
                log.error("Invalid Station Data. (" + this._symbolFieldName + ": " + symbCol + ", " +latCol  + ", " + lonCol  + ", " + idCol + ")");
                return;
            }
            //var validPointCount = 0;
            for (var i=1; i<featureList.length; i++) {
                var attrs = featureList[i].split(",");
                //mapLog.debug("processCSV: Processing csv header: " + featureList[i]);
                var pointFID = attrs[idCol];
                var pointID = pointFID.substring(pointFID.lastIndexOf(FID_SEP)+1,pointFID.length);
                if (pointID != null && pointID != "") {
                    this._points[pointID] = new CSVPoint(pointID, attrs[lonCol], attrs[latCol], attrs[symbCol], attrs, this._keys);
                    //validPointCount++;
                }
            }
            //alert("Added " + validPointCount + " csv points.");
            //for (var pId in this._points) {
            //    alert("Just added point: " +  pId + " - " + this._points[pId].getSymbol() + this._points[pId]._attrs[symbCol]);
            //}
            //mapLog.debug("CSVFeatureManager.processCSV: found " + this._points.length + " features");
            allFeaturesManager.addPoints('code', this._points);
        }
    }
}


GMLFeatureManager.prototype = new FeatureManager();

function GMLFeatureManager(symbolFieldName,geomFieldName) {
    FeatureManager.call(this,symbolFieldName);
    this._geomFieldName = geomFieldName;
}

GMLFeatureManager.prototype.parseXML = function(xmlString) {
    var myParser = new DOMParser();
    //xmlDoc = Sarissa.getDomDocument();
    //alert(pointLayerArray[layerID]);
    //TODO: Check parsing results
    this._xmlDoc = myParser.parseFromString(xmlString,"text/xml");
    this.processXML();
}

GMLFeatureManager.prototype.setXMLDoc = function(xmlDoc) {
    this._xmlDoc = xmlDoc;
    this.processXML();
}

GMLFeatureManager.prototype.getFeatures = function() {
    return this._xmlDoc.getElementsByTagName(getElementName(gmlPointsName));
}

GMLFeatureManager.prototype.getGeometries = function() {
    return this._xmlDoc.getElementsByTagName(getElementName(POINT_TAG));
}

GMLFeatureManager.prototype.processXML = function() {
    if (statistics) {
        // (Re)Initialize the global array of stats.
        symbolNameArray = new Object();
    }

    var theFeatures = this.getFeatures();
    // (Re)Initialize the associative array of features.
    this._points = new Object();
    
    for (i=0;i<theFeatures.length;i++){
        var lat,lon;
        var feature=theFeatures[i];
        var featureChildNodes = feature.childNodes;
        var pointFID = feature.getAttribute("fid");
        var pointID = pointFID.substring(pointFID.lastIndexOf(FID_SEP)+1,pointFID.length);

        var symbol = null;
        var geom = null;
        for (n=0;n<featureChildNodes.length;n++) {
            var tempChildNode = featureChildNodes[n];
            var nodeName = tempChildNode.nodeName.toUpperCase();
            if (this._symbolFieldName==nodeName) {
                symbol = Sarissa.getText(tempChildNode);
                if (geom != null) break;
            } else if (this._geomFieldName==nodeName) {
                //alert(nodeName + ":" + featureChildNodes[n] + ":" + Sarissa.getText(featureChildNodes[n]) + featureChildNodes[n].childNodes[1] + featureChildNodes[n].childNodes[1].childNodes[1]);
                if (isMSIE) {
                    geom = Sarissa.getText(featureChildNodes[n].firstChild.firstChild);
                } else {
                    geom = Sarissa.getText(featureChildNodes[n].childNodes[1].childNodes[1]).split(",");
                }
                lon = geom[0];
                lat = geom[1];
                if (symbol != null) break;
            }
        }
        //alert(lon + ":" + lat  + ":" + symbol);
        this._points[pointID] = new GMLPoint(pointID, lon, lat, symbol, feature);
        mapLog.debug("GMLFeatureManager.processXML: creating new GMLPoint(" + i + ") " + pointID);

        //Make sure that a symbol exists
        // if (symbol==null || symbol=="") {
            // symbol = DEFAULT_SYMBOL;
        // }
 
        if (statistics) {
            if (symbol!=null && symbol!="") {
                statsCount(symbol);
            } else {
                statsCount("");
            }
        }
        allFeaturesManager.addPoints('code', this._points);
    }
    mapLog.debug("GMLFeatureManager.processXML: found " + this._points.length + " features");
}

