"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewerApiShim = exports.AjaxViewerMapActionCode = exports.AjaxViewerLineStringOrPolygon = exports.enableRedlineMessagePrompt = void 0;
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var extent_1 = require("ol/extent");
var Point_1 = tslib_1.__importDefault(require("ol/geom/Point"));
var LineString_1 = tslib_1.__importDefault(require("ol/geom/LineString"));
var Polygon_1 = tslib_1.__importDefault(require("ol/geom/Polygon"));
var client_1 = require("../api/client");
var error_1 = require("../api/error");
var common_1 = require("../api/common");
var deArrayify_1 = require("../api/builders/deArrayify");
var form_frame_shim_1 = require("../components/form-frame-shim");
var command_1 = require("../api/registry/command");
var i18n_1 = require("../api/i18n");
var mapagent_1 = require("../api/builders/mapagent");
var units_1 = require("../utils/units");
var hooks_1 = require("./hooks");
var runtime_1 = require("../api/runtime");
var logger_1 = require("../utils/logger");
var map_1 = require("../actions/map");
var legend_1 = require("../actions/legend");
var taskpane_1 = require("../actions/taskpane");
var constants_1 = require("../constants");
var hooks_mapguide_1 = require("./hooks-mapguide");
var context_1 = require("../components/map-providers/context");
var dompurify_1 = require("dompurify");
function isEmptySelection(selection) {
    if (selection && selection.FeatureSet) {
        var count = 0;
        for (var _i = 0, _a = selection.FeatureSet.Layer; _i < _a.length; _i++) {
            var l = _a[_i];
            count += l.Class.ID.length;
        }
        return count === 0;
    }
    return true; //Treat undefined/null as empty
}
/**
 * This class emulates a subset of the Fusion API. This represents the top-level object named "Fusion"
 */
var FusionApiShim = /** @class */ (function () {
    function FusionApiShim(parent) {
        this.parent = parent;
        this.Event = new FusionEventApiShim();
    }
    FusionApiShim.prototype.xml2json = function (callback, response, json) {
        if (json) {
            var o = JSON.parse(response.responseText);
            callback(o);
        }
        else {
            var options = {
                onSuccess: callback,
                method: 'POST',
                parameters: { 'xml': encodeURIComponent(response.responseText) }
            };
            this.ajaxRequest('common/php/Xml2JSON.php', options);
        }
    };
    FusionApiShim.prototype.ajaxRequest = function (url, options) {
        var reqUrl = "".concat((0, runtime_1.getFusionRoot)(), "/").concat(url);
        var client = this.parent.getClient();
        var resolve = options.onSuccess || (function () { return (0, logger_1.debug)("No success handler defined for this operation"); });
        var fail = options.onFailure || options.onException || (function (_r, res) { return (0, logger_1.error)(res); });
        if (client) {
            if (typeof (options.parameters) == 'string') {
                reqUrl += "?" + options.parameters;
                fetch(reqUrl, {
                    method: "GET"
                }).then(function (res) {
                    if (!res.ok) {
                        var stat_1 = res.statusText;
                        res.text().then(function (t) {
                            fail({
                                transport: {
                                    responseText: t
                                }
                            }, new error_1.MgError(stat_1));
                        });
                    }
                    else {
                        res.text().then(function (t) { return resolve({
                            responseText: t
                        }); });
                    }
                });
            }
            else {
                fetch(reqUrl, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    method: "POST",
                    body: (0, mapagent_1.serialize)(options.parameters, false) //form
                }).then(function (res) {
                    if (!res.ok) {
                        var stat_2 = res.statusText;
                        res.text().then(function (t) {
                            fail({
                                transport: {
                                    responseText: t
                                }
                            }, new error_1.MgError(stat_2));
                        });
                    }
                    else {
                        res.text().then(function (t) { return resolve({
                            responseText: t
                        }); });
                    }
                });
            }
        }
    };
    FusionApiShim.prototype.getMapByName = function (name) {
        if (this.parent.props.map && this.parent.props.map.Name == name) {
            return new FusionWidgetApiShim(this.parent);
        }
        return undefined;
    };
    FusionApiShim.prototype.getWidgetById = function (id) {
        if (id == constants_1.FUSION_TASKPANE_NAME ||
            id == constants_1.FUSION_MAP_NAME) {
            return new FusionWidgetApiShim(this.parent);
        }
        return undefined;
    };
    FusionApiShim.prototype.getWidgetsByType = function (type) {
        if (type == constants_1.FUSION_REDLINE_NAME) {
            return [
                new FusionWidgetApiShim(this.parent)
            ];
        }
        return [];
    };
    FusionApiShim.prototype.registerForEvent = function (eventID, callback) {
        this.parent.registerForEvent(eventID, callback);
    };
    return FusionApiShim;
}());
/**
 * This class emulates the OpenLayers.Function.bind helper
 */
var OL2FunctionHelper = /** @class */ (function () {
    function OL2FunctionHelper() {
    }
    OL2FunctionHelper.prototype.bind = function (func, obj_this) {
        return func.bind(obj_this);
    };
    return OL2FunctionHelper;
}());
/**
 * This class emulates a subset of the OpenLayers 2 API
 */
var OL2Shim = /** @class */ (function () {
    function OL2Shim() {
        this.Function = new OL2FunctionHelper();
    }
    OL2Shim.prototype.i18n = function (key) {
        return (0, i18n_1.tr)(key);
    };
    return OL2Shim;
}());
/**
 * This class emulates event constants defined by Fusion
 */
var FusionEventApiShim = /** @class */ (function () {
    function FusionEventApiShim() {
    }
    Object.defineProperty(FusionEventApiShim.prototype, "MAP_SELECTION_ON", {
        get: function () { return 1; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FusionEventApiShim.prototype, "MAP_SELECTION_OFF", {
        get: function () { return 2; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FusionEventApiShim.prototype, "MAP_ACTIVE_LAYER_CHANGED", {
        get: function () { return 3; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FusionEventApiShim.prototype, "MAP_BUSY_CHANGED", {
        get: function () { return 4; },
        enumerable: false,
        configurable: true
    });
    return FusionEventApiShim;
}());
/**
 * This class emulates a digitized rectangle
 */
var OL2Rect = /** @class */ (function () {
    function OL2Rect(poly) {
        this.poly = poly;
    }
    OL2Rect.prototype.getVertices = function () {
        var coords = this.poly.getExtent();
        return [
            { x: coords[0], y: coords[1] },
            undefined,
            { x: coords[2], y: coords[3] } //2
        ];
    };
    return OL2Rect;
}());
/**
 * This class emulates an OpenLayers 2 geometry
 */
var OL2Geom = /** @class */ (function () {
    function OL2Geom(geom) {
        this.geom = geom;
    }
    Object.defineProperty(OL2Geom.prototype, "x", {
        get: function () {
            var g = this.geom;
            if (g instanceof Point_1.default) {
                return g.getCoordinates()[0];
            }
            return NaN;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(OL2Geom.prototype, "y", {
        get: function () {
            var g = this.geom;
            if (g instanceof Point_1.default) {
                return g.getCoordinates()[1];
            }
            return NaN;
        },
        enumerable: false,
        configurable: true
    });
    OL2Geom.prototype.getVertices = function () {
        var g = this.geom;
        if (g instanceof Point_1.default) {
        }
        else if (g instanceof LineString_1.default) {
            return g.getCoordinates().map(function (c) {
                return { x: c[0], y: c[1] };
            });
        }
        else if (g instanceof Polygon_1.default) {
            var ring = g.getLinearRing(0);
            if (ring) {
                return ring.getCoordinates().map(function (c) {
                    return { x: c[0], y: c[1] };
                });
            }
        }
        return [];
    };
    Object.defineProperty(OL2Geom.prototype, "CLASS_NAME", {
        get: function () {
            if (this.geom instanceof Point_1.default) {
                return "OpenLayers.Geometry.Point";
            }
            else if (this.geom instanceof LineString_1.default) {
                return "OpenLayers.Geometry.LineString";
            }
            else if (this.geom instanceof Polygon_1.default) {
                return "OpenLayers.Geometry.Polygon";
            }
            else {
                return "Unknown";
            }
        },
        enumerable: false,
        configurable: true
    });
    return OL2Geom;
}());
/**
 * This class emulates OpenLayers.Bounds
 */
var OL2Bounds = /** @class */ (function () {
    function OL2Bounds(bounds) {
        if (Array.isArray(bounds)) {
            this.left = bounds[0];
            this.bottom = bounds[1];
            this.right = bounds[2];
            this.top = bounds[3];
        }
        else {
            this.left = bounds.left;
            this.bottom = bounds.bottom;
            this.right = bounds.right;
            this.top = bounds.top;
        }
    }
    return OL2Bounds;
}());
var mRedlineMessageEnabled;
/**
 * @hidden
 */
function isRedlineMessagePromptEnabled() {
    return !!mRedlineMessageEnabled;
}
/**
 * @hidden
 */
function enableRedlineMessagePrompt(enabled) {
    mRedlineMessageEnabled = enabled;
}
exports.enableRedlineMessagePrompt = enableRedlineMessagePrompt;
/**
 * This class emulates APIs from various widgets
 */
var FusionWidgetApiShim = /** @class */ (function () {
    function FusionWidgetApiShim(parent) {
        this.parent = parent;
    }
    FusionWidgetApiShim.prototype.goHome = function () {
        this.parent.goHome();
    };
    FusionWidgetApiShim.prototype.processFeatureInfo = function (r) {
        var o = JSON.parse(r.responseText);
        if (o.FeatureInformation) {
            var norm = (0, deArrayify_1.deArrayify)(o);
            if ((0, deArrayify_1.isQueryMapFeaturesResponse)(norm)) {
                var selXml = (0, deArrayify_1.buildSelectionXml)(norm.FeatureSet);
                this.setSelection(selXml, false);
            }
        }
        else if (o.Message) {
            this.warn(o.Message);
        }
    };
    FusionWidgetApiShim.prototype.getSelectableLayers = function () {
        var layers = [];
        var map = this.parent.props.map;
        if (map && map.Layer) {
            var matches = map.Layer
                .filter(function (l) { return l.Selectable; })
                .map(function (l) {
                return { layerName: l.Name, legendLabel: l.LegendLabel };
            });
            for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {
                var l = matches_1[_i];
                layers.push(l);
            }
        }
        return layers;
    };
    Object.defineProperty(FusionWidgetApiShim.prototype, "mapWidget", {
        get: function () {
            return this;
        },
        enumerable: false,
        configurable: true
    });
    FusionWidgetApiShim.prototype.getExtentFromPoint = function (x, y, scale) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var view = viewer.getCurrentView();
            if (!scale) {
                scale = view.scale;
            }
            var res = viewer.scaleToResolution(scale);
            var size = viewer.getSize();
            var w = size[0] * res;
            var h = size[1] * res;
            return new OL2Bounds([
                x - w / 2,
                y - h / 2,
                x + w / 2,
                y + h / 2
            ]);
        }
        return undefined;
    };
    FusionWidgetApiShim.prototype.setExtents = function (bounds) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.zoomToExtent([bounds.left, bounds.bottom, bounds.right, bounds.top]);
        }
    };
    FusionWidgetApiShim.prototype.setActiveLayer = function (layer) {
        this._activeLayer = layer;
        var fusionAPI = this.parent.getFusionAPI();
        this.parent.triggerFusionEvent(fusionAPI.Event.MAP_ACTIVE_LAYER_CHANGED);
    };
    FusionWidgetApiShim.prototype.getActiveLayer = function () {
        return this._activeLayer;
    };
    FusionWidgetApiShim.prototype.clearSelection = function () {
        this.parent.ClearSelection();
    };
    FusionWidgetApiShim.prototype.cancelDigitization = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.cancelDigitization();
        }
    };
    FusionWidgetApiShim.prototype.query = function (options) {
        var _a;
        var viewer = (_a = (0, runtime_1.getViewer)()) === null || _a === void 0 ? void 0 : _a.mapguideSupport();
        var map = this.parent.props.map;
        if (map && viewer) {
            var mapName = map.Name;
            var qmo = {
                mapname: mapName,
                session: map.SessionId,
                selectionvariant: options.selectionType,
                maxfeatures: options.maxFeatures,
                geometry: options.geometry,
                layernames: options.layers
            };
            if (qmo.maxfeatures == 0) {
                qmo.maxfeatures = -1;
            }
            viewer.setSelectionXml("", qmo);
        }
    };
    FusionWidgetApiShim.prototype.setSelection = function (xml, zoomTo) {
        var _this = this;
        var viewer = (0, runtime_1.getViewer)();
        var mgSupport = viewer === null || viewer === void 0 ? void 0 : viewer.mapguideSupport();
        if (viewer && mgSupport) {
            mgSupport.setSelectionXml(xml, {
                layerattributefilter: 0 //Need to set this in order for requestdata to be respected
            }, function (selection) {
                if (zoomTo) {
                    var fact_1 = viewer.getOLFactory();
                    var bounds_1 = null;
                    if (selection != null && selection.SelectedFeatures != null) {
                        selection.SelectedFeatures.SelectedLayer.forEach(function (layer) {
                            layer.Feature.forEach(function (feat) {
                                if (feat.Bounds) {
                                    var b = feat.Bounds.split(" ").map(function (s) { return parseFloat(s); });
                                    if (bounds_1 == null) {
                                        bounds_1 = b;
                                    }
                                    else {
                                        bounds_1 = fact_1.extendExtent(bounds_1, b);
                                    }
                                }
                            });
                        });
                    }
                    if (bounds_1) {
                        var bw = (0, extent_1.getWidth)(bounds_1);
                        var bh = (0, extent_1.getHeight)(bounds_1);
                        if (bw > 0 && bh > 0) { //Don't zoom if we get 0 bounds. Cruncing bounds from selected points would do this.
                            var view = viewer.getViewForExtent(bounds_1);
                            _this.parent.ZoomToView(view.x, view.y, view.scale);
                        }
                    }
                }
            });
        }
    };
    FusionWidgetApiShim.prototype.getSelectedLayers = function () {
        var layers = [];
        var map = this.parent.props.map;
        var selectionSet = this.parent.props.selectionSet;
        if (map && map.Layer && selectionSet && selectionSet.FeatureSet) {
            var _loop_1 = function (fl) {
                var ml = map.Layer.filter(function (l) { return l.ObjectId == fl["@id"]; })[0];
                if (ml) {
                    layers.push({ legendLabel: ml.LegendLabel, layerName: ml.Name });
                }
            };
            for (var _i = 0, _a = selectionSet.FeatureSet.Layer; _i < _a.length; _i++) {
                var fl = _a[_i];
                _loop_1(fl);
            }
        }
        return layers;
    };
    FusionWidgetApiShim.prototype.isBusy = function () {
        if (this.parent.props.busyCount)
            return this.parent.props.busyCount > 0;
        return false;
    };
    FusionWidgetApiShim.prototype.isMapLoaded = function () {
        return true;
    };
    FusionWidgetApiShim.prototype.redraw = function () {
        this.parent.Refresh();
    };
    FusionWidgetApiShim.prototype.reloadMap = function () {
        this.parent.Refresh();
    };
    FusionWidgetApiShim.prototype.info = function (msg) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            this._activeToast = viewer.toastPrimary("info-sign", React.createElement("div", { className: "mg-fusion-message", dangerouslySetInnerHTML: { __html: (0, dompurify_1.sanitize)(msg) } }));
        }
    };
    FusionWidgetApiShim.prototype.warn = function (msg) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            this._activeToast = viewer.toastPrimary("warning-sign", React.createElement("div", { className: "mg-fusion-message", dangerouslySetInnerHTML: { __html: (0, dompurify_1.sanitize)(msg) } }));
        }
    };
    FusionWidgetApiShim.prototype.error = function (msg) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            this._activeToast = viewer.toastPrimary("error", React.createElement("div", { className: "mg-fusion-message", dangerouslySetInnerHTML: { __html: (0, dompurify_1.sanitize)(msg) } }));
        }
    };
    FusionWidgetApiShim.prototype.clear = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer && this._activeToast) {
            viewer.dismissToast(this._activeToast);
        }
    };
    Object.defineProperty(FusionWidgetApiShim.prototype, "mapMessagePrompt", {
        get: function () {
            return isRedlineMessagePromptEnabled();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FusionWidgetApiShim.prototype, "container", {
        get: function () {
            return this;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FusionWidgetApiShim.prototype, "ownerDocument", {
        get: function () {
            return document;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FusionWidgetApiShim.prototype, "message", {
        get: function () {
            return this;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FusionWidgetApiShim.prototype, "layerRoot", {
        get: function () {
            return this;
        },
        enumerable: false,
        configurable: true
    });
    FusionWidgetApiShim.prototype.findLayerByAttribute = function (name, value) {
        var map = this.parent.props.map;
        if (map && map.Layer) {
            var ml = map.Layer.filter(function (lyr) {
                switch (name) {
                    case "layerName":
                        return lyr.Name == value;
                }
                return false;
            })[0];
            if (ml) {
                return { layerName: ml.Name };
            }
        }
        return null;
    };
    FusionWidgetApiShim.prototype.pixToGeoMeasure = function (tolerance) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var res = viewer.getResolution();
            if (res) {
                return tolerance * res;
            }
        }
        return 0.000001; //Pull some random number
    };
    FusionWidgetApiShim.prototype.drawMap = function () {
        this.parent.Refresh();
    };
    FusionWidgetApiShim.prototype.registerForEvent = function (eventID, callback) {
        this.parent.registerForEvent(eventID, callback);
    };
    FusionWidgetApiShim.prototype.deregisterForEvent = function (eventID, callback) {
        this.parent.deregisterForEvent(eventID, callback);
    };
    FusionWidgetApiShim.toOL2Circle = function (circ) {
        var c = circ.getCenter();
        return {
            x: c[0],
            y: c[1],
            r: circ.getRadius()
        };
    };
    FusionWidgetApiShim.prototype.digitizePoint = function (_options, handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizePoint(function (pt) {
                handler(new OL2Geom(pt));
            });
        }
    };
    FusionWidgetApiShim.prototype.digitizeLine = function (_options, handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeLine(function (ln) {
                handler(new OL2Geom(ln));
            });
        }
    };
    FusionWidgetApiShim.prototype.digitizeLineString = function (_options, handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeLineString(function (lstr) {
                handler(new OL2Geom(lstr));
            });
        }
    };
    FusionWidgetApiShim.prototype.digitizeRectangle = function (_options, handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeRectangle(function (rect) {
                handler(new OL2Rect(rect));
            });
        }
    };
    FusionWidgetApiShim.prototype.digitizePolygon = function (_options, handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizePolygon(function (poly) {
                handler(new OL2Geom(poly));
            });
        }
    };
    FusionWidgetApiShim.prototype.digitizeCircle = function (_options, handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeCircle(function (circ) {
                handler(FusionWidgetApiShim.toOL2Circle(circ));
            });
        }
    };
    return FusionWidgetApiShim;
}());
var AjaxViewerLineStringOrPolygon = /** @class */ (function () {
    function AjaxViewerLineStringOrPolygon(coordinates) {
        this.coordinates = coordinates;
    }
    Object.defineProperty(AjaxViewerLineStringOrPolygon.prototype, "Count", {
        get: function () { return this.coordinates.length; },
        enumerable: false,
        configurable: true
    });
    AjaxViewerLineStringOrPolygon.prototype.Point = function (i) {
        var pt = this.coordinates[i];
        return pt;
    };
    return AjaxViewerLineStringOrPolygon;
}());
exports.AjaxViewerLineStringOrPolygon = AjaxViewerLineStringOrPolygon;
var AjaxViewerMapActionCode;
(function (AjaxViewerMapActionCode) {
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["PanMode"] = 1] = "PanMode";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["PanUp"] = 2] = "PanUp";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["PanDown"] = 3] = "PanDown";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["PanRight"] = 4] = "PanRight";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["PanLeft"] = 5] = "PanLeft";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["ZoomMode"] = 6] = "ZoomMode";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["ZoomIn"] = 7] = "ZoomIn";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["ZoomOut"] = 8] = "ZoomOut";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["ZoomRect"] = 9] = "ZoomRect";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["ZoomSelection"] = 10] = "ZoomSelection";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["ZoomExtents"] = 11] = "ZoomExtents";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["PrevView"] = 12] = "PrevView";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["NextView"] = 13] = "NextView";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["InitialView"] = 14] = "InitialView";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["SelectionMode"] = 15] = "SelectionMode";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["SelectRadius"] = 16] = "SelectRadius";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["SelectPolygon"] = 17] = "SelectPolygon";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["ClearSelection"] = 19] = "ClearSelection";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["RefreshMap"] = 20] = "RefreshMap";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["CopyMap"] = 21] = "CopyMap";
    AjaxViewerMapActionCode[AjaxViewerMapActionCode["About"] = 22] = "About";
})(AjaxViewerMapActionCode = exports.AjaxViewerMapActionCode || (exports.AjaxViewerMapActionCode = {}));
/**
 * This component installs a AJAX/Fusion viewer API compatibility layer when mounted allowing for existing
 * script content to work against this viewer.
 *
 * @export
 * @class ViewerApiShim
 * @extends {React.Component<ViewerApiShimProps, any>}
 */
var ViewerApiShimInner = /** @class */ (function (_super) {
    tslib_1.__extends(ViewerApiShimInner, _super);
    function ViewerApiShimInner(props) {
        var _this = _super.call(this, props) || this;
        _this.onFormFrameMounted = function (form) {
            _this.formFrame = form;
        };
        _this.GetMapName = function () { var _a; return (_a = _this.props.map) === null || _a === void 0 ? void 0 : _a.Name; };
        _this.GetSessionId = function () { var _a; return (_a = _this.props.map) === null || _a === void 0 ? void 0 : _a.SessionId; };
        _this.goHome = function () { var _a, _b; return (_b = (_a = _this.props).goHome) === null || _b === void 0 ? void 0 : _b.call(_a); };
        _this.us = true;
        _this.userSelectionHandlers = [];
        _this.fusionEventHandlers = {};
        _this.ol2API = new OL2Shim();
        _this.fusionAPI = new FusionApiShim(_this);
        return _this;
    }
    ViewerApiShimInner.prototype.getClient = function () {
        var _a = this.props, agentUri = _a.agentUri, agentKind = _a.agentKind;
        if (agentUri && agentKind) {
            return new client_1.Client(agentUri, agentKind);
        }
        return undefined;
    };
    // ------------------------ Fusion API support ----------------------- //
    ViewerApiShimInner.prototype.getFusionAPI = function () {
        return this.fusionAPI;
    };
    ViewerApiShimInner.prototype.registerForEvent = function (eventID, callback) {
        (0, logger_1.debug)("Fusion registerForEvent - ".concat(eventID));
        if (!this.fusionEventHandlers[eventID]) {
            this.fusionEventHandlers[eventID] = [];
        }
        this.fusionEventHandlers[eventID].push(callback);
    };
    ViewerApiShimInner.prototype.deregisterForEvent = function (eventID, callback) {
        (0, logger_1.debug)("Fusion deregisterForEvent - ".concat(eventID));
        if (this.fusionEventHandlers[eventID]) {
            var funcs = this.fusionEventHandlers[eventID].filter(function (f) { return f != callback; });
            this.fusionEventHandlers[eventID] = funcs;
        }
        else {
            (0, logger_1.debug)("No callbacks registered for fusion event - ".concat(eventID));
        }
    };
    ViewerApiShimInner.prototype.triggerFusionEvent = function (eventID) {
        if (this.fusionEventHandlers[eventID]) {
            (0, logger_1.debug)("Trigger Fusion Event ID - ".concat(eventID));
            for (var _i = 0, _a = this.fusionEventHandlers[eventID]; _i < _a.length; _i++) {
                var cb = _a[_i];
                cb.apply(null, arguments);
            }
        }
    };
    ViewerApiShimInner.prototype.fusionSelectionHandler = function (selection) {
        var eventID = isEmptySelection(selection) ? this.fusionAPI.Event.MAP_SELECTION_OFF : this.fusionAPI.Event.MAP_SELECTION_ON;
        this.triggerFusionEvent(eventID);
    };
    Object.defineProperty(ViewerApiShimInner.prototype, "mapInit", {
        // ------------------------ Map Frame -------------------------------- //
        /**
         * Indicates if the map frame is ready
         *
         * Although this not part of the "public" API, most AJAX viewer examples test for this
         * flag anyways, so we might as well emulate it here
         */
        get: function () { var _a; return ((_a = this.props.map) === null || _a === void 0 ? void 0 : _a.SessionId) != null; },
        enumerable: false,
        configurable: true
    });
    ViewerApiShimInner.prototype.ExecuteMapAction = function (code) {
        var cmdName;
        switch (code) {
            case AjaxViewerMapActionCode.About:
                cmdName = command_1.DefaultCommands.About;
                break;
            case AjaxViewerMapActionCode.ClearSelection:
                cmdName = command_1.DefaultCommands.ClearSelection;
                break;
            case AjaxViewerMapActionCode.InitialView:
                cmdName = command_1.DefaultCommands.ZoomExtents;
                break;
            case AjaxViewerMapActionCode.NextView:
                cmdName = command_1.DefaultCommands.NextView;
                break;
            case AjaxViewerMapActionCode.PanDown:
                cmdName = command_1.DefaultCommands.PanDown;
                break;
            case AjaxViewerMapActionCode.PanLeft:
                cmdName = command_1.DefaultCommands.PanLeft;
                break;
            case AjaxViewerMapActionCode.PanMode:
                cmdName = command_1.DefaultCommands.Pan;
                break;
            case AjaxViewerMapActionCode.PanRight:
                cmdName = command_1.DefaultCommands.PanRight;
                break;
            case AjaxViewerMapActionCode.PanUp:
                cmdName = command_1.DefaultCommands.PanUp;
                break;
            case AjaxViewerMapActionCode.PrevView:
                cmdName = command_1.DefaultCommands.PreviousView;
                break;
            case AjaxViewerMapActionCode.RefreshMap:
                cmdName = command_1.DefaultCommands.RefreshMap;
                break;
            case AjaxViewerMapActionCode.SelectionMode:
                cmdName = command_1.DefaultCommands.Select;
                break;
            case AjaxViewerMapActionCode.SelectPolygon:
                cmdName = command_1.DefaultCommands.SelectPolygon;
                break;
            case AjaxViewerMapActionCode.SelectRadius:
                cmdName = command_1.DefaultCommands.SelectRadius;
                break;
            case AjaxViewerMapActionCode.ZoomExtents:
                cmdName = command_1.DefaultCommands.ZoomExtents;
                break;
            case AjaxViewerMapActionCode.ZoomIn:
                cmdName = command_1.DefaultCommands.ZoomIn;
                break;
            case AjaxViewerMapActionCode.ZoomMode:
                cmdName = command_1.DefaultCommands.Zoom;
                break;
            case AjaxViewerMapActionCode.ZoomOut:
                cmdName = command_1.DefaultCommands.ZoomOut;
                break;
            case AjaxViewerMapActionCode.ZoomRect:
                cmdName = command_1.DefaultCommands.Zoom;
                break;
            case AjaxViewerMapActionCode.ZoomSelection:
                cmdName = command_1.DefaultCommands.ZoomToSelection;
                break;
            default:
                (0, logger_1.warn)("Unknown command code: ".concat(code));
                return;
        }
        var cmd = (0, command_1.getCommand)(cmdName);
        if (cmd && this.props.invokeCommand) {
            this.props.invokeCommand(cmd);
        }
    };
    ViewerApiShimInner.prototype.ClearSelection = function () {
        var _a, _b;
        (_b = (_a = (0, runtime_1.getViewer)()) === null || _a === void 0 ? void 0 : _a.mapguideSupport()) === null || _b === void 0 ? void 0 : _b.clearSelection();
    };
    ViewerApiShimInner.prototype.DigitizeCircle = function (handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeCircle(function (circle) {
                var center = circle.getCenter();
                var radius = circle.getRadius();
                handler({
                    Center: {
                        X: center[0],
                        Y: center[1]
                    },
                    Radius: radius
                });
            });
        }
    };
    ViewerApiShimInner.prototype.DigitizeLine = function (handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeLine(function (line) {
                var coords = line.getCoordinates().map(function (coord) {
                    return {
                        X: coord[0],
                        Y: coord[1]
                    };
                });
                handler(new AjaxViewerLineStringOrPolygon(coords));
            });
        }
    };
    ViewerApiShimInner.prototype.DigitizePoint = function (handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizePoint(function (pt) {
                var coords = pt.getCoordinates();
                handler({ X: coords[0], Y: coords[1] });
            });
        }
    };
    ViewerApiShimInner.prototype.DigitizePolygon = function (handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizePolygon(function (poly) {
                //Our API isn't expected to allow drawing polygons with holes, so the first (outer) ring
                //is what we're after
                var ring = poly.getLinearRing(0);
                if (ring) {
                    var coords = ring.getCoordinates().map(function (coord) {
                        return {
                            X: coord[0],
                            Y: coord[1]
                        };
                    });
                    handler(new AjaxViewerLineStringOrPolygon(coords));
                }
            });
        }
    };
    ViewerApiShimInner.prototype.DigitizeLineString = function (handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeLineString(function (line) {
                var coords = line.getCoordinates().map(function (coord) {
                    return {
                        X: coord[0],
                        Y: coord[1]
                    };
                });
                handler(new AjaxViewerLineStringOrPolygon(coords));
            });
        }
    };
    ViewerApiShimInner.prototype.DigitizeRectangle = function (handler) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.digitizeRectangle(function (rect) {
                var extent = rect.getExtent();
                handler({
                    Point1: {
                        X: extent[0],
                        Y: extent[1]
                    },
                    Point2: {
                        X: extent[2],
                        Y: extent[3]
                    }
                });
            });
        }
    };
    ViewerApiShimInner.prototype.GetCenter = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var view = viewer.getCurrentView();
            return { X: view.x, Y: view.y };
        }
        return null;
    };
    ViewerApiShimInner.prototype.GetLayers = function (onlyVisible, onlySelectable) {
        var selLayers = [];
        var _a = this.props, map = _a.map, selectionSet = _a.selectionSet;
        if (map && selectionSet && selectionSet.FeatureSet) {
            var fset = selectionSet.FeatureSet;
            var ids = fset.Layer.map(function (l) { return l["@id"]; });
            if (map.Layer) {
                for (var _i = 0, _b = map.Layer; _i < _b.length; _i++) {
                    var layer = _b[_i];
                    if (ids.indexOf(layer.ObjectId) >= 0) {
                        if (onlyVisible === true && layer.Visible === true) {
                            selLayers.push({ legend: layer.LegendLabel, name: layer.Name, objectid: layer.ObjectId });
                        }
                        if (onlySelectable === true && layer.Selectable === true) {
                            selLayers.push({ legend: layer.LegendLabel, name: layer.Name, objectid: layer.ObjectId });
                        }
                    }
                }
            }
        }
        return selLayers;
    };
    ViewerApiShimInner.prototype.GetMetersPerUnit = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            return viewer.getMetersPerUnit();
        }
        return null;
    };
    ViewerApiShimInner.prototype.GetMapHeight = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var _a = viewer.getSize(), gh = _a[1];
            return gh;
        }
        return NaN;
    };
    ViewerApiShimInner.prototype.GetMapUnitsType = function () {
        var uom = (0, units_1.getUnitOfMeasure)(this.props.sizeUnits || common_1.UnitOfMeasure.Unknown);
        return uom.name;
    };
    ViewerApiShimInner.prototype.GetMapWidth = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var gw = viewer.getSize()[0];
            return gw;
        }
        return NaN;
    };
    ViewerApiShimInner.prototype.GetScale = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var view = viewer.getCurrentView();
            return view.scale;
        }
        return null;
    };
    ViewerApiShimInner.prototype.GetSelectedLayers = function () {
        var selLayers = [];
        var _a = this.props, map = _a.map, selectionSet = _a.selectionSet;
        if (map && selectionSet && selectionSet.FeatureSet) {
            var fset = selectionSet.FeatureSet;
            var ids = fset.Layer.map(function (l) { return l["@id"]; });
            if (map.Layer) {
                for (var _i = 0, _b = map.Layer; _i < _b.length; _i++) {
                    var layer = _b[_i];
                    if (ids.indexOf(layer.ObjectId) >= 0) {
                        selLayers.push({ legend: layer.LegendLabel, name: layer.Name, objectid: layer.ObjectId });
                    }
                }
            }
        }
        return selLayers;
    };
    ViewerApiShimInner.prototype.GetSelectionXML = function () {
        var selectionSet = this.props.selectionSet;
        if (!selectionSet || !selectionSet.FeatureSet) {
            return "";
        }
        else {
            return (0, deArrayify_1.buildSelectionXml)(selectionSet.FeatureSet);
        }
    };
    ViewerApiShimInner.prototype.GetSelectedBounds = function () {
        var bounds = null;
        var selectionSet = this.props.selectionSet;
        if (selectionSet && selectionSet.SelectedFeatures) {
            var fset = selectionSet.SelectedFeatures;
            fset.SelectedLayer.forEach(function (layer) {
                layer.Feature.forEach(function (feature) {
                    var bbox = feature.Bounds
                        ? feature.Bounds.split(" ").map(function (s) { return parseFloat(s); })
                        : undefined;
                    if (bbox) {
                        if (bounds == null) {
                            bounds = { minx: bbox[0], miny: bbox[1], maxx: bbox[2], maxy: bbox[3] };
                        }
                        else {
                            if (bbox[0] < bounds.minx)
                                bounds.minx = bbox[0];
                            if (bbox[1] < bounds.miny)
                                bounds.miny = bbox[1];
                            if (bbox[2] > bounds.maxx)
                                bounds.maxx = bbox[2];
                            if (bbox[3] > bounds.maxy)
                                bounds.maxy = bbox[3];
                        }
                    }
                });
            });
        }
        return bounds;
    };
    ViewerApiShimInner.prototype.GetSelectedCount = function () {
        var count = 0;
        var selectionSet = this.props.selectionSet;
        if (selectionSet && selectionSet.FeatureSet) {
            var fset = selectionSet.FeatureSet;
            fset.Layer.forEach(function (layer) {
                layer.Class.ID.forEach(function () {
                    count++;
                });
            });
        }
        return count;
    };
    ViewerApiShimInner.prototype.GetSelectedFeatures = function () {
        var _a;
        var viewer = (_a = (0, runtime_1.getViewer)()) === null || _a === void 0 ? void 0 : _a.mapguideSupport();
        if (viewer) {
            var selection = viewer.getSelection();
            if (selection && selection.SelectedFeatures) {
                var sel = {};
                for (var _i = 0, _b = selection.SelectedFeatures.SelectedLayer; _i < _b.length; _i++) {
                    var sl = _b[_i];
                    sel[sl["@name"]] = sl.Feature.map(function (f) {
                        if (f.Bounds) {
                            var bbox = f.Bounds.split(" ").map(function (s) { return parseFloat(s); });
                            return {
                                zoom: { minx: bbox[0], miny: bbox[1], maxx: bbox[2], maxy: bbox[3] },
                                values: f.Property.map(function (p) { return ({ name: p.Name, value: p.Value }); })
                            };
                        }
                        return undefined;
                    }).filter(function (f) { return f != null; });
                }
                return sel;
            }
        }
    };
    ViewerApiShimInner.prototype.IsDigitizing = function () {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            return viewer.isDigitizing();
        }
        else {
            return false;
        }
    };
    ViewerApiShimInner.prototype.IsEnglishUnits = function () {
        return this.us;
    };
    ViewerApiShimInner.prototype.IsLatLongDisplayUnits = function () {
        return true; //This is what the AJAX viewer returns
    };
    ViewerApiShimInner.prototype.MapUnitsToLatLon = function () {
        throw new error_1.MgError("Un-implemented AJAX viewer shim API: map_frame.MapUnitsToLatLon(x, y)");
    };
    ViewerApiShimInner.prototype.Refresh = function () {
        var _a, _b;
        var viewer = (0, runtime_1.getViewer)();
        viewer === null || viewer === void 0 ? void 0 : viewer.refreshMap(common_1.RefreshMode.LayersOnly | common_1.RefreshMode.SelectionOnly);
        (_b = (_a = this.props).legendRefresh) === null || _b === void 0 ? void 0 : _b.call(_a);
    };
    ViewerApiShimInner.prototype.ScreenToMapUnits = function (x, y) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var _a = viewer.screenToMapUnits(x, y), sx = _a[0], sy = _a[1];
            return { X: sx, Y: sy };
        }
    };
    ViewerApiShimInner.prototype.SetEnglishUnits = function (usEnglish) {
        this.us = usEnglish;
    };
    ViewerApiShimInner.prototype.SetLatLongDisplayUnits = function () {
        //This is what the AJAX viewer does
    };
    ViewerApiShimInner.prototype.SetSelectionXML = function (xmlSet) {
        var _a;
        var viewer = (_a = (0, runtime_1.getViewer)()) === null || _a === void 0 ? void 0 : _a.mapguideSupport();
        if (viewer) {
            viewer.setSelectionXml(xmlSet);
        }
    };
    ViewerApiShimInner.prototype.ZoomToView = function (x, y, scale) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            viewer.zoomToView(x, y, scale);
        }
    };
    ViewerApiShimInner.prototype.SetStatusMsg = function (msg) {
        window.status = msg || ""; //Most browsers do nothing with window.status, but that is what this method does in the AJAX viewer
    };
    //This isn't in the AJAX Viewer API reference, but there are samples referencing it!
    ViewerApiShimInner.prototype.ZoomToScale = function (scale) {
        var viewer = (0, runtime_1.getViewer)();
        if (viewer) {
            var view = viewer.getCurrentView();
            viewer.zoomToView(view.x, view.y, scale);
        }
    };
    //Form frame
    ViewerApiShimInner.prototype.Submit = function (url, params, frameTarget) {
        this.formFrame.submit(url, params, frameTarget);
    };
    ViewerApiShimInner.prototype.RegisterSelectionHandler = function (handler) {
        this.userSelectionHandlers.push(handler);
        return this.userSelectionHandlers.length;
    };
    ViewerApiShimInner.prototype.UnregisterSelectionHandler = function (handler) {
        this.userSelectionHandlers = this.userSelectionHandlers.filter(function (h) { return h != handler; });
        return this.userSelectionHandlers.length;
    };
    ViewerApiShimInner.prototype.installShims = function (browserWindow) {
        var _this = this;
        browserWindow.Fusion = this.fusionAPI;
        browserWindow.OpenLayers = this.ol2API;
        browserWindow.GetMapFrame = browserWindow.GetMapFrame || (function () { return _this; });
        //NOTE: mapFrame is technically not part of the "public" API for the AJAX viewer, but since most examples test
        //for this in place of GetMapFrame(), we might as well emulate it here
        browserWindow.mapFrame = browserWindow.GetMapFrame();
        browserWindow.formFrame = browserWindow.mapFrame;
        browserWindow.ExecuteMapAction = browserWindow.ExecuteMapAction || (function (code) { return _this.ExecuteMapAction(code); });
        browserWindow.Refresh = browserWindow.Refresh || (function () { return _this.Refresh(); });
        browserWindow.SetSelectionXML = browserWindow.SetSelectionXML || (function (xmlSet) { return _this.SetSelectionXML(xmlSet); });
        browserWindow.ZoomToView = browserWindow.ZoomToView || (function (x, y, scale) { return _this.ZoomToView(x, y, scale); });
        browserWindow.GotoHomePage = browserWindow.GotoHomePage || (function () { return _this.goHome(); });
        // ======= Extended Viewer API ========== //
        browserWindow.GetViewerInterface = browserWindow.GetViewerInterface || (function () { return (0, runtime_1.getViewer)(); });
        browserWindow.RegisterSelectionHandler = browserWindow.RegisterSelectionHandler || (function (handler) { return _this.RegisterSelectionHandler(handler); });
        browserWindow.UnregisterSelectionHandler = browserWindow.UnregisterSelectionHandler || (function (handler) { return _this.UnregisterSelectionHandler(handler); });
    };
    ViewerApiShimInner.prototype.componentDidMount = function () {
        var _this = this;
        //Install shims into browser window
        var browserWindow = window;
        this.installShims(browserWindow);
        this.installShims(window.parent);
        this.RegisterSelectionHandler(function (_mapName, selection) {
            _this.fusionSelectionHandler(selection);
        });
    };
    ViewerApiShimInner.prototype.componentDidUpdate = function (prevProps) {
        var _a;
        var nextProps = this.props;
        if (nextProps.map && nextProps.selectionSet != prevProps.selectionSet) {
            for (var _i = 0, _b = this.userSelectionHandlers; _i < _b.length; _i++) {
                var handler = _b[_i];
                handler(nextProps.map.Name, (_a = nextProps.selectionSet) !== null && _a !== void 0 ? _a : undefined);
            }
        }
        if (nextProps.busyCount != prevProps.busyCount) {
            this.triggerFusionEvent(this.fusionAPI.Event.MAP_BUSY_CHANGED);
        }
    };
    ViewerApiShimInner.prototype.render = function () {
        //This is for all intents and purposes, a "background" component. There is no real DOM representation
        return React.createElement("div", null,
            React.createElement(form_frame_shim_1.FormFrameShim, { ref: this.onFormFrameMounted }));
    };
    return ViewerApiShimInner;
}(React.Component));
var ViewerApiShim = function () {
    var map = (0, hooks_mapguide_1.useActiveMapState)();
    var selectionSet = (0, hooks_1.useActiveMapSelectionSet)();
    var agentUri = (0, hooks_1.useConfiguredAgentUri)();
    var agentKind = (0, hooks_1.useConfiguredAgentKind)();
    var busyCount = (0, hooks_1.useViewerBusyCount)();
    var sizeUnits = (0, hooks_1.useViewerSizeUnits)();
    var dispatch = (0, context_1.useReduxDispatch)();
    var goHomeAction = function () { return dispatch((0, taskpane_1.goHome)()); };
    var legendRefresh = function () { return dispatch((0, legend_1.refresh)()); };
    var invokeCommandAction = function (cmd, parameters) { return dispatch((0, map_1.invokeCommand)(cmd, parameters)); };
    var setSelectionAction = function (mapName, res) { return dispatch((0, map_1.setSelection)(mapName, res)); };
    var queryMapFeaturesAction = function (mapName, options) { return dispatch((0, map_1.queryMapFeatures)(mapName, options)); };
    return React.createElement(ViewerApiShimInner, { map: map, selectionSet: selectionSet, agentUri: agentUri, agentKind: agentKind, busyCount: busyCount, sizeUnits: sizeUnits, goHome: goHomeAction, legendRefresh: legendRefresh, invokeCommand: invokeCommandAction, setSelection: setSelectionAction, queryMapFeatures: queryMapFeaturesAction });
};
exports.ViewerApiShim = ViewerApiShim;
//# sourceMappingURL=viewer-shim.js.map