"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.acknowledgeInitWarnings = exports.initLayout = exports.processLayerInMapGroup = exports.normalizeInitPayload = exports.applyInitialBaseLayerVisibility = void 0;
var tslib_1 = require("tslib");
var client_1 = require("../api/client");
var string_1 = require("../utils/string");
var actions_1 = require("../constants/actions");
var runtime_1 = require("../api/runtime");
var i18n_1 = require("../api/i18n");
var layout_1 = require("../api/registry/layout");
var logger_1 = require("../utils/logger");
function applyInitialBaseLayerVisibility(externalBaseLayers) {
    if (externalBaseLayers.length > 0) {
        // First visual base layer, first served
        var firstBase = externalBaseLayers.find(function (bl) { return bl.kind != "UTFGrid"; });
        if (firstBase) {
            firstBase.visible = true;
        }
        // Make all non-visual base layers (ie. UTFGrid) visible
        var nonVisuals = externalBaseLayers.filter(function (bl) { return bl.kind == "UTFGrid"; });
        for (var _i = 0, nonVisuals_1 = nonVisuals; _i < nonVisuals_1.length; _i++) {
            var nv = nonVisuals_1[_i];
            nv.visible = true;
        }
    }
}
exports.applyInitialBaseLayerVisibility = applyInitialBaseLayerVisibility;
function processAndDispatchInitError(error, includeStack, dispatch, opts) {
    if (error.stack) {
        dispatch({
            type: actions_1.ActionType.INIT_ERROR,
            payload: {
                error: {
                    message: error.message,
                    stack: (error.stack || "").split("\n")
                },
                includeStack: includeStack,
                options: opts
            }
        });
    }
    else {
        dispatch({
            type: actions_1.ActionType.INIT_ERROR,
            payload: {
                error: {
                    message: error.message,
                    stack: []
                },
                includeStack: includeStack,
                options: opts
            }
        });
    }
}
/**
 * @hidden
 */
function normalizeInitPayload(payload, layout) {
    if (!(0, string_1.strIsNullOrEmpty)(layout)) {
        var caps = (0, layout_1.getLayoutCapabilities)(layout);
        if (caps) {
            if (!caps.hasTaskPane) {
                (0, logger_1.debug)("Overriding hasTaskPane capability to false");
                payload.capabilities.hasTaskPane = false;
            }
        }
    }
    return payload;
}
exports.normalizeInitPayload = normalizeInitPayload;
var _counter = 0;
function processLayerInMapGroup(map, warnings, config, appDef, externalBaseLayers) {
    switch (map.Type) {
        case "Google":
            warnings.push((0, i18n_1.tr)("INIT_WARNING_UNSUPPORTED_GOOGLE_MAPS", config.locale));
            break;
        case "VirtualEarth":
            {
                //HACK: De-arrayification of arbitrary extension elements
                //is shallow (hence name/type is string[]). Do we bother to fix this?
                var _a = map.Extension.Options, name_1 = _a.name, type = _a.type;
                var sName_1 = Array.isArray(name_1) ? name_1[0] : name_1;
                var sType = Array.isArray(type) ? type[0] : type;
                var options = {};
                var bAdd = true;
                switch (sType) {
                    case "Aerial":
                    case "a":
                        options.imagerySet = "Aerial";
                        break;
                    case "AerialWithLabels":
                        options.imagerySet = "AerialWithLabels";
                        break;
                    case "Road":
                        options.imagerySet = "Road";
                        break;
                    default:
                        bAdd = false;
                        warnings.push((0, i18n_1.tr)("INIT_WARNING_BING_UNKNOWN_LAYER", config.locale, { type: type }));
                        break;
                }
                if (appDef.Extension.BingMapKey) {
                    options.key = appDef.Extension.BingMapKey;
                }
                else {
                    bAdd = false;
                    warnings.push((0, i18n_1.tr)("INIT_WARNING_BING_API_KEY_REQD", config.locale));
                }
                if (bAdd) {
                    externalBaseLayers.push({
                        name: sName_1,
                        kind: "BingMaps",
                        options: options
                    });
                }
            }
            break;
        case "OpenStreetMap":
            {
                //HACK: De-arrayification of arbitrary extension elements
                //is shallow (hence name/type is string[]). Do we bother to fix this?
                var _b = map.Extension.Options, name_2 = _b.name, type = _b.type;
                var sName_2 = Array.isArray(name_2) ? name_2[0] : name_2;
                var sType = Array.isArray(type) ? type[0] : type;
                var options = {};
                switch (sType) {
                    case "CycleMap":
                        options.url = "http://{a-c}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png";
                        break;
                    case "TransportMap":
                        options.url = "http://tile2.opencyclemap.org/transport/{z}/{x}/{y}.png";
                        break;
                }
                externalBaseLayers.push({
                    name: sName_2,
                    kind: "OSM",
                    options: options
                });
            }
            break;
        case "Stamen":
            {
                //HACK: De-arrayification of arbitrary extension elements
                //is shallow (hence name/type is string[]). Do we bother to fix this?
                var _c = map.Extension.Options, name_3 = _c.name, type = _c.type;
                var sName_3 = Array.isArray(name_3) ? name_3[0] : name_3;
                var sType = Array.isArray(type) ? type[0] : type;
                externalBaseLayers.push({
                    name: sName_3,
                    kind: "Stamen",
                    options: {
                        layer: sType
                    }
                });
            }
            break;
        case "UTFGrid":
            {
                externalBaseLayers.push({
                    name: "UTFGridSource".concat(_counter++),
                    kind: "UTFGrid",
                    options: {
                        tileJSON: {
                            scheme: "xyz",
                            grids: Array.isArray(map.Extension.UrlTemplate) ? tslib_1.__spreadArray([], map.Extension.UrlTemplate, true) : [map.Extension.UrlTemplate]
                        }
                    }
                });
            }
            break;
        case "XYZDebug":
            //HACK: De-arrayification of arbitrary extension elements
            //is shallow (hence name/type is string[]). Do we bother to fix this?
            var name_4 = map.Extension.Options.name;
            var sName = Array.isArray(name_4) ? name_4[0] : name_4;
            externalBaseLayers.push({
                name: sName,
                kind: "XYZDebug"
            });
            break;
        case "XYZ":
            {
                //HACK: De-arrayification of arbitrary extension elements
                //is shallow (hence name/type is string[]). Do we bother to fix this?
                var _d = map.Extension.Options, name_5 = _d.name, type = _d.type, attributions = _d.attributions;
                var sName_4 = Array.isArray(name_5) ? name_5[0] : name_5;
                var sType = Array.isArray(type) ? type[0] : type;
                var tilePixelRatio = 1;
                if (map.Extension.Options.tilePixelRatio) {
                    tilePixelRatio = parseInt(map.Extension.Options.tilePixelRatio[0], 10);
                }
                //NOTE: From a fusion appdef, we're expecting placeholder tokens to be in ${this_format} instead of
                //{this_format} as the primary consumer is the Fusion viewer that is based on OpenLayers 2
                //As we're not using OL2, but OL4+ the expected format is {this_format}, so we need to convert these
                //placeholder tokens
                var urls = (map.Extension.Options.urls || []).map(function (s) { return (0, string_1.strReplaceAll)(s, "${", "{"); });
                externalBaseLayers.push({
                    name: sName_4,
                    kind: "XYZ",
                    options: {
                        layer: sType,
                        urls: urls,
                        attributions: attributions,
                        tilePixelRatio: tilePixelRatio
                    }
                });
            }
            break;
    }
}
exports.processLayerInMapGroup = processLayerInMapGroup;
/**
 * Initializes the viewer
 *
 * @export
 * @param {IViewerInitCommand} cmd
 * @param {IInitAppLayout} options
 * @returns {ReduxThunkedAction}
 */
function initLayout(cmd, options) {
    var opts = tslib_1.__assign({}, options);
    return function (dispatch, getState) {
        var args = getState().config;
        //TODO: Fetch and init the string bundle earlier if "locale" is present
        //so the English init messages are seen only for a blink if requesting a
        //non-english string bundle
        if (args.agentUri && args.agentKind) {
            var client = new client_1.Client(args.agentUri, args.agentKind);
            cmd.attachClient(client);
        }
        cmd.runAsync(options).then(function (payload) {
            var _a, _b;
            var initPayload = payload;
            if (opts.initialView) {
                initPayload.initialView = tslib_1.__assign({}, opts.initialView);
            }
            if (opts.initialActiveMap) {
                initPayload.activeMapName = opts.initialActiveMap;
            }
            initPayload.initialHideGroups = opts.initialHideGroups;
            initPayload.initialHideLayers = opts.initialHideLayers;
            initPayload.initialShowGroups = opts.initialShowGroups;
            initPayload.initialShowLayers = opts.initialShowLayers;
            initPayload.featureTooltipsEnabled = opts.featureTooltipsEnabled;
            // Merge in appSettings from loaded appDef, any setting in appDef
            // already specified at viewer mount will be overwritten
            var appSettings = (_a = opts.appSettings) !== null && _a !== void 0 ? _a : {};
            var inAppSettings = (_b = payload.appSettings) !== null && _b !== void 0 ? _b : {};
            for (var k in inAppSettings) {
                appSettings[k] = inAppSettings[k];
            }
            initPayload.appSettings = appSettings;
            dispatch({
                type: actions_1.ActionType.INIT_APP,
                payload: payload
            });
            if (options.onInit) {
                var viewer = (0, runtime_1.getViewer)();
                if (viewer) {
                    options.onInit(viewer);
                }
            }
        }).catch(function (err) {
            processAndDispatchInitError(err, false, dispatch, opts);
        });
    };
}
exports.initLayout = initLayout;
function acknowledgeInitWarnings() {
    return {
        type: actions_1.ActionType.INIT_ACKNOWLEDGE_WARNINGS
    };
}
exports.acknowledgeInitWarnings = acknowledgeInitWarnings;
//# sourceMappingURL=init.js.map