"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSubMenus = exports.parseCommandsInWebLayout = exports.parseWidgetsInAppDef = exports.convertWebLayoutUIItems = exports.convertFlexLayoutUIItems = exports.isFlyoutSpec = exports.isUIWidget = void 0;
var tslib_1 = require("tslib");
var command_1 = require("./command");
var component_1 = require("./component");
var i18n_1 = require("../i18n");
var never_1 = require("../../utils/never");
var string_1 = require("../../utils/string");
var logger_1 = require("../../utils/logger");
var weblayout_1 = require("../contracts/weblayout");
var init_command_1 = require("../../actions/init-command");
var assets_1 = require("../../constants/assets");
var constants_1 = require("../../constants");
var scoped_id_1 = require("../../utils/scoped-id");
var scopedId = new scoped_id_1.ScopedId();
function isCommandSpec(cmd) {
    return !(0, string_1.strIsNullOrEmpty)(cmd.command);
}
function isUIWidget(widget) {
    return widget.WidgetType === "UiWidgetType";
}
exports.isUIWidget = isUIWidget;
/**
 * @hidden
 */
function isFlyoutSpec(item) {
    return typeof (item.children) != 'undefined';
}
exports.isFlyoutSpec = isFlyoutSpec;
function makeCommand(widget, noToolbarLabels, cmdType) {
    return { icon: widget.ImageUrl, spriteClass: widget.ImageClass, command: cmdType, label: (noToolbarLabels ? null : widget.Label), tooltip: widget.Tooltip, parameters: widget.Extension };
}
function convertWidget(widget, locale, noToolbarLabels) {
    switch (widget.Type) {
        case "Select":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Select);
        case "Pan":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Pan);
        //case "PanQuery":
        //case "PanOnClick":
        case "Zoom":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Zoom);
        case "ZoomOnClick": //Covers in and out. Look at Factor parameter
            {
                var factor = parseFloat(widget.Extension.Factor);
                if (factor >= 1.0) {
                    return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.ZoomIn);
                }
                else {
                    return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.ZoomOut);
                }
            }
        case "InitialMapView":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.ZoomExtents);
        case "ZoomToSelection":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.ZoomToSelection);
        case "ExtentHistory": //Covers prev and next. Look at Direction parameter
            {
                if (widget.Extension.Direction == "previous") {
                    return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.PreviousView);
                }
                else {
                    return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.NextView);
                }
            }
        case "CenterSelection":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.CenterSelection);
        case "About":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.About);
        case "BufferPanel":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Buffer);
        case "ClearSelection":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.ClearSelection);
        //case "ColorPicker":
        case "CoordinateTracker":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.CoordinateTracker);
        case "FeatureInfo":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.FeatureInfo);
        case "Geolocation":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Geolocation);
        //case "GoogleStreetViewer":
        case "Help":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Help);
        case "Maptip":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.MapTip);
        case "MapMenu":
            return { icon: widget.ImageUrl, spriteClass: widget.ImageClass, label: (noToolbarLabels ? null : widget.Label), tooltip: widget.Tooltip, componentName: component_1.DefaultComponentNames.MapMenu, flyoutId: "".concat(component_1.DefaultComponentNames.MapMenu, "_").concat(scopedId.next()), parameters: widget.Extension };
        case "Query":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Query);
        case "QuickPlot":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.QuickPlot);
        case "Redline":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Redline);
        case "RefreshMap":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.RefreshMap);
        //case "SaveMap":
        case "InvokeURL": //Commands with this name would've been registered beforehand
        case "Search":
            return { icon: widget.ImageUrl, spriteClass: widget.ImageClass, command: widget.Name, label: (noToolbarLabels ? null : widget.Label), tooltip: widget.Tooltip, parameters: widget.Extension };
        case "SelectPolygon":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.SelectPolygon);
        case "SelectRadius":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.SelectRadius);
        //case "SelectRadiusValue":
        case "SelectWithin":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.SelectWithin);
        case "Theme":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Theme);
        case "ViewOptions":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.ViewerOptions);
        case "ZoomToSelection":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.ZoomToSelection);
        case "Measure":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Measure);
        case "Print":
            return makeCommand(widget, noToolbarLabels, command_1.DefaultCommands.Print);
        case "BasemapSwitcher":
            return { icon: widget.ImageUrl, spriteClass: widget.ImageClass, label: (noToolbarLabels ? null : widget.Label), tooltip: widget.Tooltip, componentName: component_1.DefaultComponentNames.BaseMapSwitcher, flyoutId: "".concat(component_1.DefaultComponentNames.BaseMapSwitcher, "_").concat(scopedId.next()), parameters: widget.Extension };
        case "InvokeScript":
            return { icon: widget.ImageUrl, spriteClass: widget.ImageClass, command: widget.Name, label: (noToolbarLabels ? null : widget.Label), tooltip: widget.Tooltip, parameters: widget.Extension };
        default:
            return { error: (0, i18n_1.tr)("UNKNOWN_WIDGET", locale, { widget: widget.Type }) };
    }
}
/**
 * @hidden
 *
 * @param isStateless
 * @param items
 * @param widgetsByKey
 * @param locale
 * @param noToolbarLabels
 * @returns
 */
function convertFlexLayoutUIItems(isStateless, items, widgetsByKey, locale, noToolbarLabels) {
    if (noToolbarLabels === void 0) { noToolbarLabels = false; }
    var converted = items.map(function (item) {
        switch (item.Function) {
            case "Widget":
                {
                    var widget = widgetsByKey[item.Widget];
                    if (widget && isUIWidget(widget)) {
                        var cmd = convertWidget(widget, locale, noToolbarLabels);
                        if (isStateless && isCommandSpec(cmd) && !(0, command_1.isSupportedCommandInStatelessMode)(cmd.command)) {
                            console.warn("The widget (".concat(widget.Name, ") references a command (").concat(cmd.command, ") that is not supported in stateless mode. This widget will always be disabled"));
                        }
                        return cmd;
                    }
                }
            case "Separator":
                return { isSeparator: true };
            case "Flyout":
                return {
                    label: item.Label,
                    tooltip: item.Tooltip,
                    icon: item.ImageUrl,
                    spriteClass: item.ImageClass,
                    children: convertFlexLayoutUIItems(isStateless, item.Item, widgetsByKey, locale)
                };
            default:
                (0, never_1.assertNever)(item);
        }
        return null;
    })
        .filter(function (i) { return i != null; })
        .map(function (i) { return i; });
    return converted;
}
exports.convertFlexLayoutUIItems = convertFlexLayoutUIItems;
function tryTranslateImageUrlToSpriteClass(imageUrl) {
    switch (imageUrl) {
        case "../stdicons/icon_invokeurl.gif":
            return assets_1.SPRITE_INVOKE_URL;
        case "../stdicons/icon_invokescript.gif":
            return assets_1.SPRITE_INVOKE_SCRIPT;
    }
}
/**
 * @hidden
 *
 * @param items
 * @param cmdsByKey
 * @param locale
 * @param noToolbarLabels
 * @returns
 */
function convertWebLayoutUIItems(items, cmdsByKey, locale, noToolbarLabels) {
    if (noToolbarLabels === void 0) { noToolbarLabels = true; }
    var converted = (items || []).map(function (item) {
        if ((0, weblayout_1.isCommandItem)(item)) {
            var cmdDef = cmdsByKey[item.Command];
            if (!cmdDef) {
                (0, logger_1.warn)("Invalid reference to command: ".concat(item.Command));
                return { error: (0, i18n_1.tr)("UNKNOWN_COMMAND_REFERENCE", locale, { command: item.Command }) };
            }
            else if (cmdDef.TargetViewer != "Dwf") {
                var icon = {};
                if (cmdDef.ImageURL) {
                    icon.spriteClass = tryTranslateImageUrlToSpriteClass(cmdDef.ImageURL);
                    if (!icon.spriteClass) {
                        icon.icon = cmdDef.ImageURL;
                    }
                }
                var commonParams = {};
                if ((0, weblayout_1.isTargetedCommand)(cmdDef)) {
                    commonParams.Target = cmdDef.Target;
                    commonParams.TargetFrame = cmdDef.TargetFrame;
                }
                if ((0, weblayout_1.isBasicCommand)(cmdDef)) {
                    var action = cmdDef.Action;
                    if (action == "ZoomRectangle") {
                        action = command_1.DefaultCommands.Zoom;
                    }
                    else if (action == "FitToWindow") {
                        action = command_1.DefaultCommands.ZoomExtents;
                    }
                    else if (action == "Refresh") {
                        action = command_1.DefaultCommands.RefreshMap;
                    }
                    return tslib_1.__assign({ command: action, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams }, icon);
                }
                else {
                    switch (cmdDef["@xsi:type"]) {
                        case "ViewOptionsCommandType":
                            return { command: command_1.DefaultCommands.ViewerOptions, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams };
                        case "MeasureCommandType":
                            return { command: command_1.DefaultCommands.Measure, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams };
                        case "HelpCommandType":
                            return { command: command_1.DefaultCommands.Help, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams };
                        case "BufferCommandType":
                            return { command: command_1.DefaultCommands.Buffer, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams };
                        case "SelectWithinCommandType":
                            return { command: command_1.DefaultCommands.SelectWithin, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams };
                        case "GetPrintablePageCommandType":
                            return { command: command_1.DefaultCommands.QuickPlot, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams };
                        default:
                            return tslib_1.__assign({ command: cmdDef.Name, label: (noToolbarLabels ? null : cmdDef.Label), tooltip: cmdDef.Tooltip, parameters: commonParams }, icon);
                    }
                }
            }
        }
        else if ((0, weblayout_1.isSeparatorItem)(item)) {
            return { isSeparator: true };
        }
        else if ((0, weblayout_1.isFlyoutItem)(item)) {
            return {
                label: item.Label,
                tooltip: item.Tooltip,
                children: convertWebLayoutUIItems(item.SubItem, cmdsByKey, locale, false)
            };
        }
        else {
            (0, never_1.assertNever)(item);
        }
        return null;
    })
        .filter(function (i) { return i != null; })
        .map(function (i) { return i; });
    return converted;
}
exports.convertWebLayoutUIItems = convertWebLayoutUIItems;
function convertToCommandTarget(fusionCmdTarget) {
    //Treat empty/undefined target as new window
    if ((0, string_1.strIsNullOrEmpty)(fusionCmdTarget)) {
        return "NewWindow";
    }
    switch (fusionCmdTarget) {
        case "SearchWindow":
        case "InvokeUrlWindow":
            return "NewWindow";
        case "TaskPane":
            return "TaskPane";
        default:
            return "SpecifiedFrame";
    }
}
function parseWidgetsInAppDef(appDef, cmdRegister) {
    var taskPane;
    var viewSize;
    var hasLegend = false;
    var hasStatus = false;
    var hasNavigator = false;
    var hasSelectionPanel = false;
    var hasTaskBar = false;
    var initialTask;
    var isStatelessAppDef = (0, init_command_1.isStateless)(appDef);
    var widgetsByKey = {};
    //Register any InvokeURL and Search commands. Also set capabilities along the way
    for (var _i = 0, _a = appDef.WidgetSet; _i < _a.length; _i++) {
        var widgetSet = _a[_i];
        for (var _b = 0, _c = widgetSet.Widget; _b < _c.length; _b++) {
            var widget = _c[_b];
            var cmd = widget.Extension;
            switch (widget.Type) {
                case "TaskPane":
                    taskPane = widget;
                    break;
                case "ViewSize":
                    viewSize = widget;
                    break;
                case "Legend":
                    hasLegend = true;
                    break;
                case "SelectionPanel":
                    hasSelectionPanel = true;
                    break;
                case "CursorPosition":
                case "SelectionInfo":
                    hasStatus = true;
                    break;
                case "Navigator":
                    hasNavigator = true;
                    break;
                case "Search":
                    cmdRegister(widget.Name, {
                        layer: cmd.Layer,
                        prompt: cmd.Prompt,
                        resultColumns: cmd.ResultColumns,
                        filter: cmd.Filter,
                        matchLimit: cmd.MatchLimit,
                        title: (cmd.Title || (isUIWidget(widget) ? widget.Label : undefined)),
                        target: convertToCommandTarget(cmd.Target),
                        targetFrame: cmd.Target
                    });
                    if (isStatelessAppDef) {
                        console.warn("The search command (".concat(widget.Name, ") is not supported in stateless mode. This widget will always be disabled"));
                    }
                    break;
                case "InvokeURL":
                    cmdRegister(widget.Name, {
                        url: cmd.Url,
                        disableIfSelectionEmpty: cmd.DisableIfSelectionEmpty,
                        target: convertToCommandTarget(cmd.Target),
                        targetFrame: cmd.Target,
                        parameters: (cmd.AdditionalParameter || []).map(function (p) {
                            return { name: p.Key, value: p.Value };
                        }),
                        title: isUIWidget(widget) ? widget.Label : undefined
                    }); /*
                        if (config.isStateless && !strStartsWith(cmd.Url, "component://")) {
                            console.warn(`The InvokeURL command (${widget.Name}) is not supported in stateless mode. This widget will always be disabled`);
                        }*/
                    break;
            }
            widgetsByKey[widget.Name] = widget;
        }
    }
    if (taskPane) {
        hasTaskBar = true; //Fusion flex layouts can't control the visiblity of this
        initialTask = taskPane.Extension.InitialTask || "server/TaskPane.html";
    }
    else {
        initialTask = "server/TaskPane.html";
    }
    return {
        taskPane: taskPane,
        viewSize: viewSize,
        initialTask: initialTask,
        hasLegend: hasLegend,
        hasStatus: hasStatus,
        hasNavigator: hasNavigator,
        hasSelectionPanel: hasSelectionPanel,
        hasTaskBar: hasTaskBar,
        isStateless: isStatelessAppDef,
        widgetsByKey: widgetsByKey
    };
}
exports.parseWidgetsInAppDef = parseWidgetsInAppDef;
function parseCommandsInWebLayout(webLayout, cmdRegister) {
    var cmdsByKey = {};
    //Register any InvokeURL and Search commands
    for (var _i = 0, _a = webLayout.CommandSet.Command; _i < _a.length; _i++) {
        var cmd = _a[_i];
        if ((0, weblayout_1.isInvokeURLCommand)(cmd)) {
            cmdRegister(cmd.Name, {
                url: cmd.URL,
                disableIfSelectionEmpty: cmd.DisableIfSelectionEmpty,
                target: cmd.Target,
                targetFrame: cmd.TargetFrame,
                parameters: (cmd.AdditionalParameter || []).map(function (p) {
                    return { name: p.Key, value: p.Value };
                }),
                title: cmd.Label
            });
        }
        else if ((0, weblayout_1.isSearchCommand)(cmd)) {
            cmdRegister(cmd.Name, {
                layer: cmd.Layer,
                prompt: cmd.Prompt,
                target: cmd.Target,
                targetFrame: cmd.TargetFrame,
                resultColumns: cmd.ResultColumns,
                filter: cmd.Filter,
                matchLimit: cmd.MatchLimit,
                title: cmd.Label
            });
        }
        cmdsByKey[cmd.Name] = cmd;
    }
    return cmdsByKey;
}
exports.parseCommandsInWebLayout = parseCommandsInWebLayout;
/**
 * @hidden
 *
 * @param tbConf
 * @returns
 */
function prepareSubMenus(tbConf) {
    var prepared = {
        toolbars: {},
        flyouts: {}
    };
    var bFoundContextMenu = false;
    for (var key in tbConf) {
        if (key == constants_1.WEBLAYOUT_CONTEXTMENU) {
            bFoundContextMenu = true;
        }
        //Special cases: Task pane and Context Menu. Transfer all to flyout
        if (key == constants_1.WEBLAYOUT_TASKMENU || key == constants_1.WEBLAYOUT_CONTEXTMENU) {
            var flyoutId = key;
            prepared.flyouts[flyoutId] = {
                children: tbConf[key].items
            };
        }
        else {
            prepared.toolbars[key] = {
                items: []
            };
            for (var _i = 0, _a = tbConf[key].items; _i < _a.length; _i++) {
                var item = _a[_i];
                //Special case: contextmenu is all inline
                if (isFlyoutSpec(item) && key != constants_1.WEBLAYOUT_CONTEXTMENU) {
                    var flyoutId = "".concat(item.label, "_").concat(scopedId.next());
                    prepared.toolbars[key].items.push({
                        label: item.label,
                        tooltip: item.tooltip,
                        icon: item.icon,
                        spriteClass: item.spriteClass,
                        flyoutId: flyoutId
                    });
                    prepared.flyouts[flyoutId] = {
                        children: item.children
                    };
                }
                else {
                    prepared.toolbars[key].items.push(item);
                }
            }
        }
    }
    return [prepared, bFoundContextMenu];
}
exports.prepareSubMenus = prepareSubMenus;
//# sourceMappingURL=command-spec.js.map