"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewerInitCommand = exports.isStateless = exports.isMapDefinition = exports.getMapDefinitionsFromFlexLayout = exports.buildSubjectLayerDefn = void 0;
var tslib_1 = require("tslib");
var init_1 = require("./init");
var common_1 = require("../api/common");
var command_spec_1 = require("../api/registry/command-spec");
var array_1 = require("../utils/array");
var logger_1 = require("../utils/logger");
var command_1 = require("../api/registry/command");
var i18n_1 = require("../api/i18n");
var constants_1 = require("../constants");
var actions_1 = require("../constants/actions");
var url_1 = require("../utils/url");
var error_1 = require("../api/error");
var string_1 = require("../utils/string");
var TYPE_SUBJECT = "SubjectLayer";
var TYPE_EXTERNAL = "External";
function getMapGuideConfiguration(appDef) {
    var configs = [];
    if (appDef.MapSet) {
        for (var _i = 0, _a = appDef.MapSet.MapGroup; _i < _a.length; _i++) {
            var mg = _a[_i];
            for (var _b = 0, _c = mg.Map; _b < _c.length; _b++) {
                var map = _c[_b];
                if (map.Type == "MapGuide") {
                    configs.push([mg["@id"], map]);
                }
            }
        }
    }
    return configs;
}
function tryExtractMapMetadata(extension) {
    var ext = {};
    for (var k in extension) {
        if ((0, string_1.strStartsWith)(k, "Meta_")) {
            var sk = k.substring("Meta_".length);
            ext[sk] = extension[k];
        }
    }
    return ext;
}
function buildSubjectLayerDefn(name, map) {
    var _a, _b, _c;
    var st = map.Extension.source_type;
    var initiallyVisible = (_a = map.Extension.initially_visible) !== null && _a !== void 0 ? _a : true;
    var sp = {};
    var lo = {};
    var meta = {};
    var keys = Object.keys(map.Extension);
    var popupTemplate = map.Extension.popup_template;
    var selectable = (_b = map.Extension.is_selectable) !== null && _b !== void 0 ? _b : true;
    var disableHover = (_c = map.Extension.disable_hover) !== null && _c !== void 0 ? _c : false;
    for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
        var k = keys_1[_i];
        var spidx = k.indexOf("source_param_");
        var loidx = k.indexOf("layer_opt_");
        var midx = k.indexOf("meta_");
        if (spidx == 0) {
            var kn = k.substring("source_param_".length);
            sp[kn] = map.Extension[k];
        }
        else if (loidx == 0) {
            var kn = k.substring("layer_opt_".length);
            lo[kn] = map.Extension[k];
        }
        else if (midx == 0) {
            var kn = k.substring("meta_".length);
            meta[kn] = map.Extension[k];
        }
    }
    var sl = {
        name: name,
        description: map.Extension.layer_description,
        displayName: map.Extension.display_name,
        driverName: map.Extension.driver_name,
        type: st,
        layerOptions: lo,
        sourceParams: sp,
        meta: (Object.keys(meta).length > 0 ? meta : undefined),
        initiallyVisible: initiallyVisible,
        selectable: selectable,
        disableHover: disableHover,
        popupTemplate: popupTemplate,
        vectorStyle: map.Extension.vector_layer_style
    };
    if (map.Extension.cluster) {
        sl.cluster = tslib_1.__assign({}, map.Extension.cluster);
    }
    return sl;
}
exports.buildSubjectLayerDefn = buildSubjectLayerDefn;
function getMapDefinitionsFromFlexLayout(appDef) {
    var _a;
    var maps = [];
    var configs = getMapGuideConfiguration(appDef);
    if (configs.length > 0) {
        for (var _i = 0, configs_1 = configs; _i < configs_1.length; _i++) {
            var c = configs_1[_i];
            maps.push({
                name: c[0],
                mapDef: c[1].Extension.ResourceId,
                metadata: tryExtractMapMetadata(c[1].Extension)
            });
        }
    }
    if ((_a = appDef.MapSet) === null || _a === void 0 ? void 0 : _a.MapGroup) {
        for (var _b = 0, _c = appDef.MapSet.MapGroup; _b < _c.length; _b++) {
            var mGroup = _c[_b];
            for (var _d = 0, _e = mGroup.Map; _d < _e.length; _d++) {
                var map = _e[_d];
                if (map.Type == TYPE_SUBJECT) {
                    var name_1 = mGroup["@id"];
                    maps.push(buildSubjectLayerDefn(name_1, map));
                }
            }
        }
    }
    if (maps.length == 0)
        throw new error_1.MgError("No Map Definition or subject layer found in Application Definition");
    return maps;
}
exports.getMapDefinitionsFromFlexLayout = getMapDefinitionsFromFlexLayout;
function isMapDefinition(arg) {
    return arg.mapDef != null;
}
exports.isMapDefinition = isMapDefinition;
function isStateless(appDef) {
    var _a;
    // This appdef is stateless if:
    //
    //  1. It has a Stateless extension property set to "true" (ie. The author has opted-in to this feature)
    //  2. No MapGuide Map Definitions were found in the appdef
    if (((_a = appDef.Extension) === null || _a === void 0 ? void 0 : _a.Stateless) == "true")
        return true;
    try {
        var maps = getMapDefinitionsFromFlexLayout(appDef);
        for (var _i = 0, maps_1 = maps; _i < maps_1.length; _i++) {
            var m = maps_1[_i];
            if (isMapDefinition(m)) {
                return false;
            }
        }
        return true;
    }
    catch (e) {
        return true;
    }
}
exports.isStateless = isStateless;
var ViewerInitCommand = /** @class */ (function () {
    function ViewerInitCommand(dispatch) {
        this.dispatch = dispatch;
    }
    ViewerInitCommand.prototype.initLocaleAsync = function (options) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var locale, r, res;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        locale = options.locale;
                        if (!(locale != i18n_1.DEFAULT_LOCALE)) return [3 /*break*/, 4];
                        return [4 /*yield*/, fetch("strings/".concat(locale, ".json"))];
                    case 1:
                        r = _a.sent();
                        if (!r.ok) return [3 /*break*/, 3];
                        return [4 /*yield*/, r.json()];
                    case 2:
                        res = _a.sent();
                        (0, i18n_1.registerStringBundle)(locale, res);
                        // Dispatch the SET_LOCALE as it is safe to change UI strings at this point
                        this.dispatch({
                            type: actions_1.ActionType.SET_LOCALE,
                            payload: locale
                        });
                        (0, logger_1.info)("Registered string bundle for locale: ".concat(locale));
                        return [3 /*break*/, 4];
                    case 3:
                        //TODO: Push warning to init error/warning reducer when we implement it
                        (0, logger_1.warn)("Failed to register string bundle for locale: ".concat(locale));
                        _a.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    ViewerInitCommand.prototype.getExtraProjectionsFromFlexLayout = function (appDef) {
        //The only widget we care about is the coordinate tracker
        var epsgs = [];
        for (var _i = 0, _a = appDef.WidgetSet; _i < _a.length; _i++) {
            var ws = _a[_i];
            for (var _b = 0, _c = ws.Widget; _b < _c.length; _b++) {
                var w = _c[_b];
                if (w.Type == "CoordinateTracker") {
                    var ps = w.Extension.Projection || [];
                    for (var _d = 0, ps_1 = ps; _d < ps_1.length; _d++) {
                        var p = ps_1[_d];
                        epsgs.push(p.split(':')[1]);
                    }
                }
                else if (w.Type == "CursorPosition") {
                    var dp = w.Extension.DisplayProjection;
                    if (dp) {
                        epsgs.push(dp.split(':')[1]);
                    }
                }
            }
        }
        return (0, array_1.makeUnique)(epsgs);
    };
    ViewerInitCommand.prototype.initFromAppDefCoreAsync = function (appDef, options, mapsByName, warnings) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var _c, taskPane, hasTaskBar, hasStatus, hasNavigator, hasSelectionPanel, hasLegend, viewSize, widgetsByKey, isStateless, initialTask, locale, featureTooltipsEnabled, config, tbConf, _i, _d, widgetSet, _e, _f, cont, tbName, _g, _h, w, mapsDict, maps, _j, firstMapName, firstSessionId, _k, tb, bFoundContextMenu, settings, _l, _m, s, sn, sv;
            return tslib_1.__generator(this, function (_o) {
                _c = (0, command_spec_1.parseWidgetsInAppDef)(appDef, command_1.registerCommand), taskPane = _c.taskPane, hasTaskBar = _c.hasTaskBar, hasStatus = _c.hasStatus, hasNavigator = _c.hasNavigator, hasSelectionPanel = _c.hasSelectionPanel, hasLegend = _c.hasLegend, viewSize = _c.viewSize, widgetsByKey = _c.widgetsByKey, isStateless = _c.isStateless, initialTask = _c.initialTask;
                locale = options.locale, featureTooltipsEnabled = options.featureTooltipsEnabled;
                config = {};
                config.isStateless = isStateless;
                tbConf = {};
                //Now build toolbar layouts
                for (_i = 0, _d = appDef.WidgetSet; _i < _d.length; _i++) {
                    widgetSet = _d[_i];
                    for (_e = 0, _f = widgetSet.Container; _e < _f.length; _e++) {
                        cont = _f[_e];
                        tbName = cont.Name;
                        tbConf[tbName] = { items: (0, command_spec_1.convertFlexLayoutUIItems)(isStateless, cont.Item, widgetsByKey, locale) };
                    }
                    for (_g = 0, _h = widgetSet.Widget; _g < _h.length; _g++) {
                        w = _h[_g];
                        if (w.Type == "CursorPosition") {
                            config.coordinateProjection = w.Extension.DisplayProjection;
                            config.coordinateDecimals = w.Extension.Precision;
                            config.coordinateDisplayFormat = w.Extension.Template;
                        }
                    }
                }
                mapsDict = mapsByName;
                maps = this.setupMaps(appDef, mapsDict, config, warnings, locale);
                if (appDef.Title) {
                    document.title = appDef.Title || document.title;
                }
                _j = this.establishInitialMapNameAndSession(mapsDict), firstMapName = _j[0], firstSessionId = _j[1];
                _k = (0, command_spec_1.prepareSubMenus)(tbConf), tb = _k[0], bFoundContextMenu = _k[1];
                if (!bFoundContextMenu) {
                    warnings.push((0, i18n_1.tr)("INIT_WARNING_NO_CONTEXT_MENU", locale, { containerName: constants_1.WEBLAYOUT_CONTEXTMENU }));
                }
                settings = {};
                if (Array.isArray((_b = (_a = appDef.Extension) === null || _a === void 0 ? void 0 : _a.ViewerSettings) === null || _b === void 0 ? void 0 : _b.Setting)) {
                    for (_l = 0, _m = appDef.Extension.ViewerSettings.Setting; _l < _m.length; _l++) {
                        s = _m[_l];
                        sn = s["@name"][0];
                        sv = s["@value"][0];
                        settings[sn] = sv;
                    }
                }
                return [2 /*return*/, (0, init_1.normalizeInitPayload)({
                        appSettings: settings,
                        activeMapName: firstMapName,
                        initialUrl: (0, url_1.ensureParameters)(initialTask, firstMapName, firstSessionId, locale),
                        featureTooltipsEnabled: featureTooltipsEnabled,
                        locale: locale,
                        maps: maps,
                        config: config,
                        capabilities: {
                            hasTaskPane: (taskPane != null),
                            hasTaskBar: hasTaskBar,
                            hasStatusBar: hasStatus,
                            hasNavigator: hasNavigator,
                            hasSelectionPanel: hasSelectionPanel,
                            hasLegend: hasLegend,
                            hasToolbar: (Object.keys(tbConf).length > 0),
                            hasViewSize: (viewSize != null)
                        },
                        toolbars: tb,
                        warnings: warnings,
                        initialActiveTool: common_1.ActiveMapTool.Pan
                    }, options.layout)];
            });
        });
    };
    return ViewerInitCommand;
}());
exports.ViewerInitCommand = ViewerInitCommand;
//# sourceMappingURL=init-command.js.map