"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.App = void 0;
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var layout_1 = require("../api/registry/layout");
var init_1 = require("../actions/init");
var error_1 = require("../components/error");
var i18n_1 = require("../api/i18n");
var asset_1 = require("../utils/asset");
var runtime_1 = require("../api/runtime");
var context_1 = require("../components/context");
var core_1 = require("@blueprintjs/core");
var hooks_1 = require("./hooks");
var url_state_1 = require("./url-state");
var logger_1 = require("../utils/logger");
var template_1 = require("../actions/template");
var context_2 = require("../components/map-providers/context");
var dompurify_1 = require("dompurify");
var AppInner = /** @class */ (function (_super) {
    tslib_1.__extends(AppInner, _super);
    function AppInner(props) {
        var _this = _super.call(this, props) || this;
        _this.initErrorRenderer = function (err) {
            var _a = _this.props, configuredLocale = _a.configuredLocale, initOptions = _a.initOptions;
            var locale = configuredLocale;
            if (initOptions && initOptions.locale) {
                locale = initOptions.locale;
            }
            //Not showing stack as the error cases are well-defined here and we know where they
            //originate from
            return React.createElement(core_1.Callout, { intent: core_1.Intent.DANGER, title: (0, i18n_1.tr)("INIT_ERROR_TITLE", locale), icon: "error" }, _this.renderErrorMessage(err, locale, initOptions || {}));
        };
        _this.state = {
            isLoading: true
        };
        return _this;
    }
    AppInner.prototype.componentDidMount = function () {
        var _a;
        var _b = this.props, onInit = _b.onInit, setElementVisibility = _b.setElementVisibility, mapguide = _b.mapguide, initLayout = _b.initLayout, locale = _b.locale, resourceId = _b.resourceId, externalBaseLayers = _b.externalBaseLayers, initCommand = _b.initCommand, appSettings = _b.appSettings;
        var _c = (0, url_state_1.getStateFromUrl)(this.props.urlPropsIgnore), urlLocale = _c.locale, urlResource = _c.resource, urlSession = _c.session, urlX = _c.x, urlY = _c.y, urlFeatureTooltip = _c.ft, urlScale = _c.scale, urlMap = _c.map, urlShowLayers = _c.sl, urlHideLayers = _c.hl, urlShowGroups = _c.sg, urlHideGroups = _c.hg;
        if (setElementVisibility && (mapguide === null || mapguide === void 0 ? void 0 : mapguide.initialElementVisibility)) {
            var _d = mapguide.initialElementVisibility, taskpane = _d.taskpane, legend = _d.legend, selection = _d.selection;
            var states = {
                taskPaneVisible: typeof (taskpane) != 'undefined' ? taskpane : true,
                legendVisible: typeof (legend) != 'undefined' ? legend : true,
                selectionPanelVisible: typeof (selection) != 'undefined' ? selection : true
            };
            setElementVisibility(states);
        }
        (0, logger_1.debug)("Asset root is: ".concat((0, asset_1.getAssetRoot)()));
        if (mapguide === null || mapguide === void 0 ? void 0 : mapguide.fusionRoot) {
            (0, runtime_1.setFusionRoot)(mapguide.fusionRoot);
        }
        if (initLayout) {
            var ftArgs = void 0;
            if (typeof (urlFeatureTooltip) != 'undefined') {
                ftArgs = {
                    featureTooltipsEnabled: urlFeatureTooltip
                };
            }
            var amArgs = void 0;
            if (urlMap) {
                amArgs = {
                    initialActiveMap: urlMap
                };
            }
            var ivArgs = void 0;
            if (urlX && urlY && urlScale) {
                ivArgs = {
                    initialView: {
                        x: urlX,
                        y: urlY,
                        scale: urlScale
                    }
                };
            }
            var slArgs = void 0;
            if (urlShowLayers) {
                slArgs = {
                    initialShowLayers: tslib_1.__spreadArray([], urlShowLayers, true)
                };
            }
            var hlArgs = void 0;
            if (urlHideLayers) {
                hlArgs = {
                    initialHideLayers: tslib_1.__spreadArray([], urlHideLayers, true)
                };
            }
            var sgArgs = void 0;
            if (urlShowGroups) {
                sgArgs = {
                    initialShowGroups: tslib_1.__spreadArray([], urlShowGroups, true)
                };
            }
            var hgArgs = void 0;
            if (urlHideGroups) {
                hgArgs = {
                    initialHideGroups: tslib_1.__spreadArray([], urlHideGroups, true)
                };
            }
            var args = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({
                resourceId: urlResource !== null && urlResource !== void 0 ? urlResource : resourceId,
                locale: (_a = urlLocale !== null && urlLocale !== void 0 ? urlLocale : locale) !== null && _a !== void 0 ? _a : i18n_1.DEFAULT_LOCALE,
                externalBaseLayers: externalBaseLayers,
                session: urlSession !== null && urlSession !== void 0 ? urlSession : mapguide === null || mapguide === void 0 ? void 0 : mapguide.session,
                onInit: onInit,
                layout: typeof (this.props.layout) == 'string' ? this.props.layout : undefined,
                appSettings: appSettings
            }, (ftArgs !== null && ftArgs !== void 0 ? ftArgs : {})), (amArgs !== null && amArgs !== void 0 ? amArgs : {})), (ivArgs !== null && ivArgs !== void 0 ? ivArgs : {})), (slArgs !== null && slArgs !== void 0 ? slArgs : {})), (hlArgs !== null && hlArgs !== void 0 ? hlArgs : {})), (sgArgs !== null && sgArgs !== void 0 ? sgArgs : {})), (hgArgs !== null && hgArgs !== void 0 ? hgArgs : {}));
            initLayout(initCommand, args);
        }
    };
    AppInner.prototype.componentDidUpdate = function (prevProps) {
        var _a, _b, _c, _d;
        var nextProps = this.props;
        var curUrlState = (0, url_state_1.getStateFromUrl)();
        //Preserve locale/resources/session if already present in url
        var nextUrlState = {
            locale: (_a = curUrlState.locale) !== null && _a !== void 0 ? _a : this.props.locale,
            session: (_b = curUrlState.session) !== null && _b !== void 0 ? _b : (_c = this.props.mapguide) === null || _c === void 0 ? void 0 : _c.session
        };
        if (typeof (this.props.resourceId) == 'string') {
            nextUrlState.resource = (_d = curUrlState.resource) !== null && _d !== void 0 ? _d : this.props.resourceId;
        }
        if (nextProps.featureTooltipsEnabled != prevProps.featureTooltipsEnabled) {
            nextUrlState.ft = nextProps.featureTooltipsEnabled;
        }
        if (nextProps.map != null && prevProps.map != nextProps.map) {
            this.setState({ isLoading: false });
        }
        if (nextProps.activeMapName) {
            var am = nextProps.activeMapName;
            nextUrlState.map = am;
        }
        if (nextProps.map) {
            if (nextProps.map.currentView) {
                var _e = nextProps.map.currentView, x = _e.x, y = _e.y, scale = _e.scale;
                nextUrlState.x = x;
                nextUrlState.y = y;
                nextUrlState.scale = scale;
            }
            var mgs = nextProps.map.mapguide;
            if (mgs) {
                var rtm = mgs.runtimeMap;
                var showGroups = mgs.showGroups, showLayers = mgs.showLayers, hideGroups = mgs.hideGroups, hideLayers = mgs.hideLayers;
                var sg = [];
                var hg = [];
                var sl = [];
                var hl = [];
                if (rtm === null || rtm === void 0 ? void 0 : rtm.Group) {
                    for (var _i = 0, _f = rtm.Group; _i < _f.length; _i++) {
                        var g = _f[_i];
                        if (showGroups.indexOf(g.ObjectId) >= 0) {
                            sg.push(g.Name);
                        }
                        else if (hideGroups.indexOf(g.ObjectId) >= 0) {
                            hg.push(g.Name);
                        }
                    }
                }
                if (rtm === null || rtm === void 0 ? void 0 : rtm.Layer) {
                    for (var _g = 0, _h = rtm.Layer; _g < _h.length; _g++) {
                        var l = _h[_g];
                        if (showLayers.indexOf(l.ObjectId) >= 0) {
                            sl.push(l.Name);
                        }
                        else if (hideLayers.indexOf(l.ObjectId) >= 0) {
                            hl.push(l.Name);
                        }
                    }
                }
                if (sg.length > 0)
                    nextUrlState.sg = sg;
                if (hg.length > 0)
                    nextUrlState.hg = hg;
                if (sl.length > 0)
                    nextUrlState.sl = sl;
                if (hl.length > 0)
                    nextUrlState.hl = hl;
                if (rtm) {
                    var SessionId = rtm.SessionId;
                    nextUrlState.session = SessionId;
                }
            }
        }
        if (!(0, url_state_1.areStatesEqual)(curUrlState, nextUrlState))
            (0, url_state_1.updateUrl)(nextUrlState, undefined, nextProps.urlPropsIgnore);
        //else
        //    console.log("Skip pointless url state update");
    };
    AppInner.prototype.renderErrorMessage = function (err, locale, args) {
        var _this = this;
        var msg = err.message;
        switch (msg) {
            case "MgConnectionFailedException":
                {
                    var arg = { __html: (0, dompurify_1.sanitize)((0, i18n_1.tr)("INIT_ERROR_NO_CONNECTION", locale)) };
                    return React.createElement("div", { dangerouslySetInnerHTML: arg });
                }
            case "MgResourceNotFoundException":
                {
                    var arg = { __html: (0, dompurify_1.sanitize)((0, i18n_1.tr)("INIT_ERROR_RESOURCE_NOT_FOUND", locale, { resourceId: args.resourceId })) };
                    return React.createElement("div", { dangerouslySetInnerHTML: arg });
                }
            case "MgSessionExpiredException":
                {
                    var arg = { __html: (0, dompurify_1.sanitize)((0, i18n_1.tr)("INIT_ERROR_EXPIRED_SESSION", locale, { sessionId: args.session })) };
                    return React.createElement("div", { dangerouslySetInnerHTML: arg });
                }
            default:
                {
                    var arg = { __html: (0, dompurify_1.sanitize)(msg) };
                    var stack_1 = (0, error_1.normalizeStack)(err);
                    return React.createElement("div", null,
                        React.createElement("div", { dangerouslySetInnerHTML: arg }),
                        (function () {
                            if (_this.props.includeStack === true && stack_1.length > 0) {
                                return React.createElement("div", null,
                                    React.createElement("p", null, "Stack Trace"),
                                    React.createElement("ul", null, stack_1.map(function (ln, i) { return React.createElement("li", { key: "stack-line-".concat(i) }, ln); })));
                            }
                        })());
                }
        }
    };
    AppInner.prototype.render = function () {
        var _a = this.props, layout = _a.layout, configuredLocale = _a.configuredLocale, error = _a.error;
        var isLoading = this.state.isLoading;
        this.props.mapguide;
        if (error) {
            return React.createElement(error_1.Error, { error: error, errorRenderer: this.initErrorRenderer });
        }
        else {
            //NOTE: Locale may not have been set at this point, so use default
            var locale = configuredLocale;
            if (isLoading) {
                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)("INIT", locale), description: (0, i18n_1.tr)("INIT_DESC", locale) });
            }
            else {
                var layoutEl = typeof (layout) == 'string' ? (0, layout_1.getLayout)(layout) : layout.factory;
                if (layoutEl) {
                    return React.createElement(context_1.AppContextProvider, { mapguide: this.props.mapguide }, layoutEl());
                }
                else {
                    return React.createElement(error_1.Error, { error: (0, i18n_1.tr)("ERR_UNREGISTERED_LAYOUT", locale, { layout: layout }) });
                }
            }
        }
    };
    return AppInner;
}(React.Component));
var App = function (props) {
    var error = (0, hooks_1.useInitError)();
    var includeStack = (0, hooks_1.useInitErrorStack)();
    var initOptions = (0, hooks_1.useInitErrorOptions)();
    var configuredLocale = (0, hooks_1.useViewerLocale)();
    var map = (0, hooks_1.useActiveMapBranch)();
    var activeMapName = (0, hooks_1.useActiveMapName)();
    var ftEnabled = (0, hooks_1.useViewerFeatureTooltipsEnabled)();
    var dispatch = (0, context_2.useReduxDispatch)();
    var initLayoutAction = function (cmd, args) { return dispatch((0, init_1.initLayout)(cmd, args)); };
    var setElementVisibility = function (state) { return dispatch((0, template_1.setElementStates)(state)); };
    return React.createElement(AppInner, tslib_1.__assign({ error: error, includeStack: includeStack, initOptions: initOptions, featureTooltipsEnabled: ftEnabled, configuredLocale: configuredLocale, map: map, activeMapName: activeMapName, initLayout: initLayoutAction, setElementVisibility: setElementVisibility }, props));
};
exports.App = App;
//# sourceMappingURL=app.js.map