"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CSV_COLUMN_ALIASES = exports.CsvFormatDriver = void 0;
var tslib_1 = require("tslib");
var GeoJSON_1 = tslib_1.__importDefault(require("ol/format/GeoJSON"));
var parsed_features_1 = require("./parsed-features");
var string_1 = require("../../utils/string");
var Papa = require("papaparse");
var CsvFormatDriver = /** @class */ (function () {
    function CsvFormatDriver(aliases) {
        this.aliases = aliases;
        this.type = "CSV";
    }
    CsvFormatDriver.prototype.tryParse = function (size, text) {
        var aliases = this.aliases;
        var type = this.type;
        return new Promise(function (resolve, reject) {
            Papa.parse(text, {
                header: true,
                complete: function (results) {
                    var _this = this;
                    var _a, _b;
                    if (!results.data || results.data.length == 0) {
                        reject(new Error("No data parsed. Probably not a CSV file"));
                    }
                    else {
                        if (results.meta.fields) {
                            var parsed = void 0;
                            var _loop_1 = function (alias) {
                                if (parsed) {
                                    return "break";
                                }
                                var xc = (_a = results.meta.fields.filter(function (s) { return s.toLowerCase() == alias.xColumn.toLowerCase(); })) === null || _a === void 0 ? void 0 : _a[0];
                                var yc = (_b = results.meta.fields.filter(function (s) { return s.toLowerCase() == alias.yColumn.toLowerCase(); })) === null || _b === void 0 ? void 0 : _b[0];
                                // We found the columns, but before we accept this set, the columns
                                // in question must be numeric. Being CSV and all, we'll use the most
                                // scientific method to determine this: Sample the first row of data /s
                                if (!(0, string_1.strIsNullOrEmpty)(xc) && !(0, string_1.strIsNullOrEmpty)(yc)) {
                                    var first = results.data[0];
                                    var firstX = parseFloat(first[xc]);
                                    var firstY = parseFloat(first[yc]);
                                    if (first && !isNaN(firstX) && !isNaN(firstY)) {
                                        var json = {
                                            type: 'FeatureCollection',
                                            features: []
                                        };
                                        for (var _c = 0, _d = results.data; _c < _d.length; _c++) {
                                            var d = _d[_c];
                                            var x = parseFloat(d[xc]);
                                            var y = parseFloat(d[yc]);
                                            if (!isNaN(x) && !isNaN(y)) {
                                                var f = {
                                                    type: 'Feature',
                                                    geometry: {
                                                        coordinates: [x, y],
                                                        type: 'Point'
                                                    },
                                                    properties: d
                                                };
                                                delete f.properties[xc];
                                                delete f.properties[yc];
                                                json.features.push(f);
                                            }
                                        }
                                        var fmt = new GeoJSON_1.default();
                                        var features_1 = fmt.readFeatures(json);
                                        var propNames = [];
                                        if (features_1.length > 0) {
                                            var first_1 = features_1[0];
                                            for (var _e = 0, _f = first_1.getKeys(); _e < _f.length; _e++) {
                                                var k = _f[_e];
                                                if (k == first_1.getGeometryName()) {
                                                    continue;
                                                }
                                                propNames.push(k);
                                            }
                                        }
                                        var pfs = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) {
                                            return [2 /*return*/, features_1];
                                        }); }); };
                                        parsed = new parsed_features_1.ParsedFeatures(type, size, pfs, features_1.length > 0, ["Point"], propNames);
                                        return "break";
                                    }
                                }
                            };
                            //Run through the alias list and see if we get any matches
                            for (var _i = 0, aliases_1 = aliases; _i < aliases_1.length; _i++) {
                                var alias = aliases_1[_i];
                                var state_1 = _loop_1(alias);
                                if (state_1 === "break")
                                    break;
                            }
                            if (parsed) {
                                resolve(parsed);
                            }
                            else {
                                reject(new Error("Data successfully parsed as CSV, but coordinate columns could not be found"));
                            }
                        }
                        else {
                            reject(new Error("No fields found in CSV metadata"));
                        }
                    }
                }
            });
        });
    };
    return CsvFormatDriver;
}());
exports.CsvFormatDriver = CsvFormatDriver;
exports.CSV_COLUMN_ALIASES = [
    { xColumn: "lon", yColumn: "lat" },
    { xColumn: "lng", yColumn: "lat" },
    { xColumn: "longitude", yColumn: "latitude" },
    { xColumn: "x", yColumn: "y" },
    { xColumn: "easting", yColumn: "northing" }
];
//# sourceMappingURL=csv-driver.js.map