"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddWfsLayer = void 0;
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var common_1 = require("../../api/common");
var core_1 = require("@blueprintjs/core");
var i18n_1 = require("../../api/i18n");
var error_1 = require("../error");
var client_1 = require("../../api/client");
var wfs_capabilities_parser_1 = require("./wfs-capabilities-parser");
var wfs_capabilities_panel_1 = require("./wfs-capabilities-panel");
var Vector_1 = tslib_1.__importDefault(require("ol/source/Vector"));
var Vector_2 = tslib_1.__importDefault(require("ol/layer/Vector"));
var GeoJSON_1 = tslib_1.__importDefault(require("ol/format/GeoJSON"));
var url_1 = require("../../utils/url");
var projections_1 = require("../../api/registry/projections");
var layer_manager_1 = require("../../api/layer-manager");
var runtime_1 = require("../../api/runtime");
var ol_style_helpers_1 = require("../../api/ol-style-helpers");
var ol_style_contracts_1 = require("../../api/ol-style-contracts");
var add_manage_layers_1 = require("../../containers/add-manage-layers");
/**
 * @hidden
 */
var AddWfsLayer = function (props) {
    var locale = props.locale;
    var _a = React.useState(""), wfsUrl = _a[0], setWfsUrl = _a[1];
    var _b = React.useState(false), loadingCapabilities = _b[0], setLoadingCapabilities = _b[1];
    var _c = React.useState(undefined), caps = _c[0], setCaps = _c[1];
    var _d = React.useState(undefined), error = _d[0], setError = _d[1];
    var onAddLayer = function (name, version, format, origCrs, epsgCode, wfsWgs84Bounds) {
        var viewer = (0, runtime_1.getViewer)();
        if (caps && viewer) {
            (0, projections_1.ensureProjection)(epsgCode, locale, origCrs).then(function (_a) {
                var resolvedProj = _a[1];
                var sourceProj = viewer.getProjection();
                //TODO: For correctness, we should be using the URL from the ows:Get element of the
                //GetFeature operations metadata instead of just re-computing the WFS GetFeature URL
                //relative to the capabilities URL that was entered
                var parsed = (0, url_1.parseUrl)(wfsUrl);
                var typeNameKey = "typename";
                if (version == "2.0.0") { //WFS 2.0.0 want typename(s) over typename
                    typeNameKey = "typenames";
                }
                var urlTemplate = "".concat(parsed.url, "?service=WFS&version=").concat(version, "&request=GetFeature&").concat(typeNameKey, "=").concat(encodeURIComponent(name), "&outputFormat=").concat(encodeURIComponent(format), "&srsName=").concat(encodeURIComponent(origCrs));
                var sourceUrl;
                var strategy;
                var vectorFmt = new GeoJSON_1.default({
                    dataProjection: resolvedProj,
                    featureProjection: sourceProj
                });
                // FIXME: I can't seem to get bbox strategy working in general :(
                if (false) {
                    /*if (repsg == 4326 || repsg == 3857) {
                        urlTemplate += `&bbox={view_extent}`;
                        sourceUrl = function (extent) {
                            const xfextent = transformExtent(extent, sourceProj, resolvedProj);
                            const reqUrl = strReplaceAll(urlTemplate, "{view_extent}", xfextent.join(','));
                            return reqUrl;
                        }
                        strategy = bbox;
                        // We need to "decorate" the underlying loadFeaturesXhr loader so that
                        // we have the means to call busy worker incrementing/decrementing
                        innerLoader = loadFeaturesXhr(sourceUrl, vectorFmt, () => { //success
                            viewer.addImageLoaded();
                            props.onRemoveLayerBusyWorker(name);
                        }, () => { //failure
                            viewer.addImageLoaded();
                            props.onRemoveLayerBusyWorker(name);
                        });*/
                }
                else {
                    sourceUrl = urlTemplate;
                }
                var source = new Vector_1.default({
                    format: vectorFmt,
                    url: sourceUrl,
                    strategy: strategy /*,
                    loader: innerLoader ? (function() {
                        viewer.addImageLoading();
                        props.onAddLayerBusyWorker(name);
                        innerLoader?.apply(source, arguments);
                    }) : undefined*/
                });
                var layer = new Vector_2.default({
                    source: source,
                    className: "external-vector-layer" //This is to avoid false positives for map.forEachLayerAtPixel
                });
                layer.set(common_1.LayerProperty.LAYER_TYPE, "WFS");
                layer.set(common_1.LayerProperty.IS_EXTERNAL, true);
                layer.set(common_1.LayerProperty.IS_SELECTABLE, true);
                layer.set(common_1.LayerProperty.IS_GROUP, false);
                if (wfsWgs84Bounds) {
                    layer.set(common_1.LayerProperty.WGS84_BBOX, wfsWgs84Bounds);
                }
                (0, ol_style_helpers_1.setOLVectorLayerStyle)(layer, ol_style_contracts_1.DEFAULT_VECTOR_LAYER_STYLE, undefined);
                viewer.getLayerManager().addLayer(name, layer);
                viewer.toastSuccess("success", (0, i18n_1.tr)("ADDED_LAYER", locale, { name: name }));
                var li = (0, layer_manager_1.getLayerInfo)(layer, true);
                (0, add_manage_layers_1.zoomToLayerExtents)(li.name, viewer);
                props.onLayerAdded(li);
            });
        }
    };
    var onLoadCaps = function () {
        setCaps(undefined);
        setLoadingCapabilities(true);
        var client = new client_1.Client("", "mapagent");
        client.getText(wfsUrl).then(function (s) {
            var parser = new wfs_capabilities_parser_1.WfsCapabilitiesParser();
            var caps = parser.parse(s);
            setLoadingCapabilities(false);
            setCaps(caps);
            setError(undefined);
        }).catch(function (err) {
            setLoadingCapabilities(false);
            setCaps(undefined);
            setError(err);
        });
    };
    var onWmsUrlChange = function (e) {
        setWfsUrl(e.target.value);
    };
    return React.createElement("div", null,
        React.createElement(core_1.ControlGroup, { fill: true },
            React.createElement(core_1.InputGroup, { leftIcon: "geosearch", placeholder: (0, i18n_1.tr)("ADD_WFS_LAYER_URL", locale), value: wfsUrl, onChange: onWmsUrlChange, readOnly: loadingCapabilities, rightElement: React.createElement(core_1.Button, { intent: core_1.Intent.PRIMARY, icon: "arrow-right", onClick: onLoadCaps, disabled: loadingCapabilities }) })),
        React.createElement("br", null),
        React.createElement("div", null, (function () {
            if (loadingCapabilities) {
                return React.createElement(core_1.NonIdealState, { icon: React.createElement(core_1.Spinner, { intent: core_1.Intent.NONE, size: core_1.Spinner.SIZE_LARGE }), title: (0, i18n_1.tr)("ADD_WFS_LAYER_LOADING", locale), description: (0, i18n_1.tr)("ADD_WFS_LAYER_LOADING_DESC", locale) });
            }
            else {
                if (caps) {
                    return React.createElement(wfs_capabilities_panel_1.WfsCapabilitiesPanel, { onAddLayer: onAddLayer, capabilities: caps, locale: locale });
                }
                else if (error) {
                    return React.createElement(error_1.Error, { error: error });
                }
                else {
                    return React.createElement(core_1.NonIdealState, { icon: "issue", title: (0, i18n_1.tr)("ADD_WFS_LAYER_NO_LAYERS", locale), description: (0, i18n_1.tr)("WFS_NO_LAYER_DESCRIPTION", locale) });
                }
            }
        })()));
};
exports.AddWfsLayer = AddWfsLayer;
//# sourceMappingURL=add-wfs-layer.js.map