"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectedFeaturesTooltip = void 0;
var tslib_1 = require("tslib");
var Overlay_1 = tslib_1.__importDefault(require("ol/Overlay"));
var Image_1 = tslib_1.__importDefault(require("ol/layer/Image"));
var Tile_1 = tslib_1.__importDefault(require("ol/layer/Tile"));
var ImageWMS_1 = tslib_1.__importDefault(require("ol/source/ImageWMS"));
var TileWMS_1 = tslib_1.__importDefault(require("ol/source/TileWMS"));
var GeoJSON_1 = tslib_1.__importDefault(require("ol/format/GeoJSON"));
var i18n_1 = require("../../api/i18n");
var common_1 = require("../../api/common");
var client_1 = require("../../api/client");
var wfs_capabilities_panel_1 = require("../layer-manager/wfs-capabilities-panel");
var string_1 = require("../../utils/string");
var ol_style_helpers_1 = require("../../api/ol-style-helpers");
var stickybits_1 = tslib_1.__importDefault(require("stickybits"));
var dompurify_1 = require("dompurify");
function defaultPopupContentRenderer(feat, locale, popupConfig) {
    var _a, _b, _c, _d;
    var html = "";
    var bClustered = (0, ol_style_helpers_1.isClusteredFeature)(feat);
    var title = (_a = popupConfig === null || popupConfig === void 0 ? void 0 : popupConfig.title) !== null && _a !== void 0 ? _a : (0, i18n_1.tr)("SEL_FEATURE_PROPERTIES", locale);
    var size = (_b = (0, ol_style_helpers_1.getClusterSubFeatures)(feat)) === null || _b === void 0 ? void 0 : _b.length;
    ;
    if (bClustered && size > 1) {
        title = (_d = (_c = popupConfig === null || popupConfig === void 0 ? void 0 : popupConfig.clusteredTitle) === null || _c === void 0 ? void 0 : _c.call(popupConfig, size)) !== null && _d !== void 0 ? _d : (0, i18n_1.tr)("SEL_CLUSTER_PROPERTIES", locale, { size: size });
    }
    html += "<div class='selected-popup-header'><div>" + (0, dompurify_1.sanitize)(title) + "</div><a id='feat-popup-closer' class='closer' href='#'>[x]</a><div class='clearit'></div></div>";
    var renderForMultipleSanitized = function (subFeatures) {
        var table = "<table class='selected-popup-cluster-table'>";
        var fheadings = (popupConfig === null || popupConfig === void 0 ? void 0 : popupConfig.propertyMappings)
            ? popupConfig.propertyMappings.filter(function (pm) { return pm.name != subFeatures[0].getGeometryName(); }).map(function (pm) { return pm.value; })
            : Object.keys(subFeatures[0].getProperties()).filter(function (pn) { return pn != subFeatures[0].getGeometryName(); });
        var fprops = (popupConfig === null || popupConfig === void 0 ? void 0 : popupConfig.propertyMappings)
            ? popupConfig.propertyMappings.map(function (pm) { return pm.value; })
            : Object.keys(subFeatures[0].getProperties()).filter(function (pn) { return pn != subFeatures[0].getGeometryName(); });
        table += "<thead><tr>";
        for (var _i = 0, fheadings_1 = fheadings; _i < fheadings_1.length; _i++) {
            var heading = fheadings_1[_i];
            table += "<th>".concat((0, dompurify_1.sanitize)(heading), "</th>");
        }
        table += "</tr></thead>";
        table += "<tbody>";
        for (var _a = 0, subFeatures_1 = subFeatures; _a < subFeatures_1.length; _a++) {
            var f = subFeatures_1[_a];
            table += "<tr>";
            for (var _b = 0, fprops_1 = fprops; _b < fprops_1.length; _b++) {
                var property = fprops_1[_b];
                var val = f.get(property);
                table += "<td>".concat((0, dompurify_1.sanitize)(val), "</td>");
            }
            table += "</tr>";
        }
        table += "</tbody>";
        table += "</table>";
        return table;
    };
    var renderForSingleSanitized = function (feature) {
        var _a, _b, _c;
        var linkFragment;
        var table = "<table class='selected-popup-single-properties-table'>";
        table += "<tbody>";
        var f = feature.getProperties();
        var pc = 0;
        if (popupConfig === null || popupConfig === void 0 ? void 0 : popupConfig.propertyMappings) {
            for (var _i = 0, _d = popupConfig.propertyMappings; _i < _d.length; _i++) {
                var pm = _d[_i];
                if (pm.name == feat.getGeometryName()) {
                    continue;
                }
                table += "<tr>";
                table += "<td class='property-name-cell'>" + (0, dompurify_1.sanitize)(pm.value) + "</td>";
                table += "<td class='property-value-cell'>" + (0, dompurify_1.sanitize)(f[pm.name]) + "</td>";
                table += "</tr>";
                pc++;
            }
        }
        else {
            for (var key in f) {
                if (key == feat.getGeometryName()) {
                    continue;
                }
                table += "<tr>";
                table += "<td class='property-name-cell'>" + (0, dompurify_1.sanitize)(key) + "</td>";
                table += "<td class='property-value-cell'>" + (0, dompurify_1.sanitize)(f[key]) + "</td>";
                table += "</tr>";
                pc++;
            }
        }
        table += "</tbody>";
        table += "</table>";
        if (popupConfig === null || popupConfig === void 0 ? void 0 : popupConfig.linkProperty) {
            var _e = popupConfig.linkProperty, name_1 = _e.name, label = _e.label, linkTarget = _e.linkTarget;
            var linkHref = void 0;
            if (typeof (name_1) == 'string') {
                linkHref = encodeURI(f[name_1]);
            }
            else {
                var expr = name_1.expression;
                var url = expr;
                var pBegin = (_a = name_1.placeholderBegin) !== null && _a !== void 0 ? _a : "{";
                var pEnd = (_b = name_1.placeholderEnd) !== null && _b !== void 0 ? _b : "}";
                var tokens = (0, string_1.extractPlaceholderTokens)(expr, pBegin, pEnd);
                for (var _f = 0, tokens_1 = tokens; _f < tokens_1.length; _f++) {
                    var t = tokens_1[_f];
                    var al = encodeURIComponent((_c = f[t]) !== null && _c !== void 0 ? _c : "");
                    url = (0, string_1.strReplaceAll)(url, "".concat(pBegin).concat(t).concat(pEnd), al);
                }
                linkHref = url;
            }
            if (!(0, string_1.strIsNullOrEmpty)(linkHref)) {
                linkFragment = "<div class='select-popup-single-link-wrapper'><a href=\"".concat((0, dompurify_1.sanitize)(linkHref), "\" target='").concat((0, dompurify_1.sanitize)(linkTarget), "'>").concat((0, dompurify_1.sanitize)(label), "</a></div>");
            }
        }
        return [table, pc, linkFragment];
    };
    var singlePopupContentRender = function (feature, appendHtml) {
        var _a = renderForSingleSanitized(feature), table = _a[0], pc = _a[1], linkFragment = _a[2];
        if (pc > 0) {
            appendHtml("<div class='selected-popup-content-wrapper'>".concat(table, "</div>"));
        }
        else {
            appendHtml("<div class='selected-popup-content-none'>" + (0, dompurify_1.sanitize)((0, i18n_1.tr)("SEL_FEATURE_PROPERTIES_NONE", locale)) + "</div>");
        }
        if (!(0, string_1.strIsNullOrEmpty)(linkFragment)) {
            appendHtml(linkFragment);
        }
    };
    if (bClustered) {
        var subFeatures = (0, ol_style_helpers_1.getClusterSubFeatures)(feat);
        if (subFeatures.length == 1) {
            singlePopupContentRender(subFeatures[0], function (h) { return html += h; });
        }
        else {
            var table = renderForMultipleSanitized(subFeatures);
            html += "<div class='selected-popup-content-wrapper'>".concat(table, "</div>");
        }
    }
    else {
        singlePopupContentRender(feat, function (h) { return html += h; });
    }
    return html;
}
var SelectedFeaturesTooltip = /** @class */ (function () {
    function SelectedFeaturesTooltip(map, parent) {
        var _this = this;
        this.parent = parent;
        this.setPopupCloseHandler = function () {
            if (_this.closerEl) {
                _this.closerEl.onclick = _this.closePopup;
            }
        };
        this.closePopup = function (e) {
            e.preventDefault();
            _this.hide();
            if (_this.closerEl) {
                _this.closerEl.onclick = null;
            }
            return false;
        };
        this.featureTooltipElement = document.createElement("div");
        this.featureTooltipElement.addEventListener("mouseover", function () { return _this.isMouseOverTooltip = true; });
        this.featureTooltipElement.addEventListener("mouseout", function () { return _this.isMouseOverTooltip = false; });
        this.featureTooltipElement.className = 'selected-tooltip';
        this.featureTooltip = new Overlay_1.default({
            element: this.featureTooltipElement,
            offset: [15, 0],
            positioning: "center-left"
        });
        this.map = map;
        this.map.addOverlay(this.featureTooltip);
        this.enabled = true;
        this.isMouseOverTooltip = false;
    }
    SelectedFeaturesTooltip.prototype.dispose = function () {
        this.featureTooltip.dispose();
    };
    Object.defineProperty(SelectedFeaturesTooltip.prototype, "isMouseOver", {
        get: function () { return this.isMouseOverTooltip; },
        enumerable: false,
        configurable: true
    });
    SelectedFeaturesTooltip.prototype.isEnabled = function () {
        return this.enabled;
    };
    SelectedFeaturesTooltip.prototype.setEnabled = function (enabled) {
        this.enabled = enabled;
        if (!this.enabled) {
            this.featureTooltipElement.innerHTML = "";
            this.featureTooltipElement.classList.add("tooltip-hidden");
        }
    };
    SelectedFeaturesTooltip.prototype.hide = function () {
        this.featureTooltipElement.innerHTML = "";
        this.featureTooltipElement.classList.add("tooltip-hidden");
    };
    SelectedFeaturesTooltip.prototype.queryWmsFeatures = function (currentLayerSet, layerMgr, coord, resolution, bAppendMode, callback) {
        var _a, _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var selected, client, format, wmsSources, currentWmsSource, layers, _i, layers_1, layer, wmsLayer, source, _d, wmsSources_1, pair, layer, source, url, layerName, augs, resp, json, srcProj, epsg, features, popupConf, html;
            return tslib_1.__generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        selected = 0;
                        client = new client_1.Client("", "mapagent");
                        format = new GeoJSON_1.default();
                        wmsSources = [];
                        currentWmsSource = currentLayerSet === null || currentLayerSet === void 0 ? void 0 : currentLayerSet.tryGetWmsSource();
                        if (currentWmsSource) {
                            wmsSources.push(currentWmsSource);
                        }
                        layers = layerMgr.getLayers().filter(function (l) { return l.visible && l.selectable && l.type == "WMS"; });
                        for (_i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
                            layer = layers_1[_i];
                            wmsLayer = layerMgr.getLayer(layer.name);
                            if (wmsLayer instanceof Image_1.default || wmsLayer instanceof Tile_1.default) {
                                source = wmsLayer.getSource();
                                if (source instanceof ImageWMS_1.default || source instanceof TileWMS_1.default) {
                                    wmsSources.push([wmsLayer, source]);
                                }
                            }
                        }
                        _d = 0, wmsSources_1 = wmsSources;
                        _e.label = 1;
                    case 1:
                        if (!(_d < wmsSources_1.length)) return [3 /*break*/, 4];
                        pair = wmsSources_1[_d];
                        layer = pair[0], source = pair[1];
                        url = source.getFeatureInfoUrl(coord, resolution, this.map.getView().getProjection(), {
                            'INFO_FORMAT': "application/json"
                        });
                        if (!url) return [3 /*break*/, 3];
                        layerName = layer.get(common_1.LayerProperty.LAYER_NAME);
                        augs = callback.getWmsRequestAugmentations();
                        if (augs[layerName]) {
                            url = augs[layerName](url);
                        }
                        return [4 /*yield*/, client.getText(url)];
                    case 2:
                        resp = _e.sent();
                        json = JSON.parse(resp);
                        if (((_a = json.features) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                            srcProj = source.getProjection();
                            if (!srcProj) {
                                epsg = (0, wfs_capabilities_panel_1.parseEpsgCodeFromCRS)((_c = (_b = json.crs) === null || _b === void 0 ? void 0 : _b.properties) === null || _c === void 0 ? void 0 : _c.name);
                                if (epsg) {
                                    srcProj = "EPSG:".concat(epsg);
                                }
                                else { //Type narrowing hack
                                    srcProj = undefined;
                                }
                            }
                            features = format.readFeatures(resp, {
                                dataProjection: srcProj,
                                featureProjection: this.map.getView().getProjection()
                            });
                            this.featureTooltip.setPosition(coord);
                            popupConf = layer.get(common_1.LayerProperty.SELECTED_POPUP_CONFIGURATION);
                            html = this.generateFeatureHtml(layerName, features[0], callback.getLocale(), popupConf);
                            callback.addClientSelectedFeature(features[0], layer);
                            currentLayerSet === null || currentLayerSet === void 0 ? void 0 : currentLayerSet.clearWmsSelectionOverlay();
                            currentLayerSet === null || currentLayerSet === void 0 ? void 0 : currentLayerSet.addWmsSelectionOverlay(features[0]);
                            callback.addFeatureToHighlight(features[0], bAppendMode);
                            selected++;
                            this.featureTooltipElement.innerHTML = html;
                            (0, stickybits_1.default)(".selected-popup-cluster-table th");
                            this.closerEl = document.getElementById("feat-popup-closer");
                            this.setPopupCloseHandler();
                            if (html == "") {
                                this.featureTooltipElement.classList.add("tooltip-hidden");
                            }
                            else {
                                this.featureTooltipElement.classList.remove("tooltip-hidden");
                            }
                            return [2 /*return*/, true];
                        }
                        _e.label = 3;
                    case 3:
                        _d++;
                        return [3 /*break*/, 1];
                    case 4:
                        // Clear if there was no selection made
                        if (selected == 0) {
                            callback.addFeatureToHighlight(undefined, false);
                            this.hide();
                        }
                        return [2 /*return*/, false];
                }
            });
        });
    };
    SelectedFeaturesTooltip.prototype.generateFeatureHtml = function (layerName, feat, locale, popupConfig) {
        if (layerName) {
            var customRenderer = this.parent.getSelectionPopupRenderer(layerName);
            if (customRenderer) {
                return customRenderer(feat, locale, popupConfig);
            }
            else {
                return defaultPopupContentRenderer(feat, locale, popupConfig);
            }
        }
        return defaultPopupContentRenderer(feat, locale, popupConfig);
    };
    SelectedFeaturesTooltip.prototype.showSelectedVectorFeatures = function (features, pixel, featureToLayerMap, locale) {
        var coords = this.map.getCoordinateFromPixel(pixel);
        if (features.getLength() > 0) {
            this.featureTooltip.setPosition(coords);
            var f_1 = features.item(0);
            var popupConf = void 0;
            var pair = featureToLayerMap.find(function (_a) {
                var feat = _a[0], _ = _a[1];
                return feat == f_1;
            });
            var layerName = void 0;
            if (pair) {
                var layer = pair[1];
                popupConf = layer.get(common_1.LayerProperty.SELECTED_POPUP_CONFIGURATION);
                layerName = layer.get(common_1.LayerProperty.LAYER_NAME);
            }
            var html = this.generateFeatureHtml(layerName, f_1, locale, popupConf);
            this.featureTooltipElement.innerHTML = html;
            (0, stickybits_1.default)(".selected-popup-cluster-table th");
            this.closerEl = document.getElementById("feat-popup-closer");
            this.setPopupCloseHandler();
            if (html == "") {
                this.featureTooltipElement.classList.add("tooltip-hidden");
            }
            else {
                this.featureTooltipElement.classList.remove("tooltip-hidden");
            }
        }
        else {
            this.featureTooltipElement.innerHTML = "";
            this.featureTooltipElement.classList.add("tooltip-hidden");
        }
    };
    return SelectedFeaturesTooltip;
}());
exports.SelectedFeaturesTooltip = SelectedFeaturesTooltip;
//# sourceMappingURL=selected-features.js.map