"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDefaultCommands = exports.buildTargetedCommand = void 0;
var tslib_1 = require("tslib");
var command_1 = require("./registry/command");
var common_1 = require("./common");
var i18n_1 = require("../api/i18n");
var component_1 = require("../api/registry/component");
var assets_1 = require("../constants/assets");
var map_1 = require("../actions/map");
var modal_1 = require("../actions/modal");
var legend_1 = require("../actions/legend");
var template_1 = require("../actions/template");
var react_1 = tslib_1.__importDefault(require("react"));
var react_dom_1 = tslib_1.__importDefault(require("react-dom"));
function panMap(dispatch, viewer, value) {
    var settings = {
        "right": [2, 1],
        "left": [0, 1],
        "down": [0, 1],
        "up": [0, 3]
    };
    var view = viewer.getCurrentView();
    var current_center = [view.x, view.y];
    var currentExtent = viewer.getCurrentExtent();
    var newPos;
    var direction = settings[value];
    if (value == "right" || value == "left") {
        newPos = [
            currentExtent[direction[0]],
            current_center[direction[1]]
        ];
    }
    else {
        newPos = [
            current_center[direction[0]],
            currentExtent[direction[1]]
        ];
    }
    dispatch((0, map_1.setCurrentView)({ x: newPos[0], y: newPos[1], scale: view.scale }));
}
function buildTargetedCommand(config, parameters) {
    var cmdTarget = (parameters || {}).Target;
    var cmdDef = {
        target: cmdTarget || "NewWindow"
    };
    if (config.capabilities.hasTaskPane && cmdTarget == "TaskPane") {
        cmdDef.target = "TaskPane";
    }
    if (cmdTarget == "SpecifiedFrame") {
        cmdDef.target = cmdTarget;
        cmdDef.targetFrame = (parameters || {}).TargetFrame;
    }
    return cmdDef;
}
exports.buildTargetedCommand = buildTargetedCommand;
/**
 * Registers the default set of commands into the command registry. This is automatically called by the default viewer
 * bundle. If creating your own viewer bundle, be sure to call this function in your entry point, or individually register
 * the commands you want to make available in your custom viewer bundle
 *
 * @export
 */
function initDefaultCommands() {
    //Select Tool
    (0, command_1.registerCommand)(command_1.DefaultCommands.Select, {
        iconClass: assets_1.SPRITE_SELECT,
        selected: function (state) {
            return state.activeTool === common_1.ActiveMapTool.Select;
        },
        enabled: function () { return true; },
        invoke: function (dispatch) {
            return dispatch((0, map_1.setActiveTool)(common_1.ActiveMapTool.Select));
        }
    });
    //Pan Tool
    (0, command_1.registerCommand)(command_1.DefaultCommands.Pan, {
        iconClass: assets_1.SPRITE_PAN,
        selected: function (state) {
            return state.activeTool === common_1.ActiveMapTool.Pan;
        },
        enabled: function () { return true; },
        invoke: function (dispatch) {
            return dispatch((0, map_1.setActiveTool)(common_1.ActiveMapTool.Pan));
        }
    });
    //Zoom Tool
    (0, command_1.registerCommand)(command_1.DefaultCommands.Zoom, {
        iconClass: assets_1.SPRITE_ZOOM_IN,
        selected: function (state) {
            return state.activeTool === common_1.ActiveMapTool.Zoom;
        },
        enabled: function () { return true; },
        invoke: function (dispatch) {
            return dispatch((0, map_1.setActiveTool)(common_1.ActiveMapTool.Zoom));
        }
    });
    //Zoom in
    (0, command_1.registerCommand)(command_1.DefaultCommands.ZoomIn, {
        iconClass: assets_1.SPRITE_ZOOM_IN_FIXED,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (_dispatch, _getState, viewer) {
            if (viewer) {
                viewer.zoomDelta(1);
            }
        }
    });
    //Zoom Out
    (0, command_1.registerCommand)(command_1.DefaultCommands.ZoomOut, {
        iconClass: assets_1.SPRITE_ZOOM_OUT_FIXED,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (_dispatch, _getState, viewer) {
            if (viewer) {
                viewer.zoomDelta(-1);
            }
        }
    });
    //Pan Left
    (0, command_1.registerCommand)(command_1.DefaultCommands.PanLeft, {
        iconClass: assets_1.SPRITE_PAN_WEST,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, _getState, viewer) {
            if (viewer) {
                panMap(dispatch, viewer, "left");
            }
        }
    });
    //Pan Right
    (0, command_1.registerCommand)(command_1.DefaultCommands.PanRight, {
        iconClass: assets_1.SPRITE_PAN_EAST,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, _getState, viewer) {
            if (viewer) {
                panMap(dispatch, viewer, "right");
            }
        }
    });
    //Pan Up
    (0, command_1.registerCommand)(command_1.DefaultCommands.PanUp, {
        iconClass: assets_1.SPRITE_PAN_NORTH,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, _getState, viewer) {
            if (viewer) {
                panMap(dispatch, viewer, "up");
            }
        }
    });
    //Pan Down
    (0, command_1.registerCommand)(command_1.DefaultCommands.PanDown, {
        iconClass: assets_1.SPRITE_PAN_SOUTH,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, _getState, viewer) {
            if (viewer) {
                panMap(dispatch, viewer, "down");
            }
        }
    });
    //About
    (0, command_1.registerCommand)(command_1.DefaultCommands.About, {
        iconClass: assets_1.SPRITE_ABOUT,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, getState) {
            dispatch((0, modal_1.showModalComponent)({
                modal: {
                    title: (0, i18n_1.tr)("ABOUT", getState().config.locale),
                    backdrop: true
                },
                name: component_1.DefaultComponentNames.About,
                component: component_1.DefaultComponentNames.About
            }));
        }
    });
    //Help
    (0, command_1.registerCommand)(command_1.DefaultCommands.Help, {
        iconClass: assets_1.SPRITE_HELP,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, getState) {
            dispatch((0, modal_1.showModalUrl)({
                modal: {
                    title: (0, i18n_1.tr)("HELP", getState().config.locale),
                    backdrop: true
                },
                name: command_1.DefaultCommands.Help,
                url: "help/index.html"
            }));
        }
    });
    //Measure
    (0, command_1.registerCommand)(command_1.DefaultCommands.Measure, {
        iconClass: assets_1.SPRITE_MEASURE,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, getState, _viewer, parameters) {
            var config = getState().config;
            var url = "component://Measure";
            var cmdDef = buildTargetedCommand(config, parameters);
            (0, command_1.openUrlInTarget)(command_1.DefaultCommands.Measure, cmdDef, config.capabilities.hasTaskPane, dispatch, url, (0, i18n_1.tr)("MEASURE", config.locale));
        }
    });
    //Initial Center and scale
    (0, command_1.registerCommand)(command_1.DefaultCommands.RestoreView, {
        iconClass: assets_1.SPRITE_INITIAL_CENTER,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (_dispatch, getState, viewer) {
            if (viewer) {
                var view = (0, common_1.getInitialView)(getState());
                if (view != null) {
                    viewer.zoomToView(view.x, view.y, view.scale);
                }
                else {
                    viewer.initialView();
                }
            }
        }
    });
    //Zoom Extents
    (0, command_1.registerCommand)(command_1.DefaultCommands.ZoomExtents, {
        iconClass: assets_1.SPRITE_ZOOM_FULL,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (_dispatch, _getState, viewer) {
            if (viewer) {
                viewer.initialView();
            }
        }
    });
    //Refresh Map
    (0, command_1.registerCommand)(command_1.DefaultCommands.RefreshMap, {
        iconClass: assets_1.SPRITE_ICON_REFRESHMAP,
        selected: function () { return false; },
        enabled: command_1.CommandConditions.isNotBusy,
        invoke: function (dispatch, _getState, viewer) {
            if (viewer) {
                viewer.refreshMap(common_1.RefreshMode.LayersOnly | common_1.RefreshMode.SelectionOnly);
                dispatch((0, legend_1.refresh)());
            }
        }
    });
    //Previous View
    (0, command_1.registerCommand)(command_1.DefaultCommands.PreviousView, {
        iconClass: assets_1.SPRITE_VIEW_BACK,
        selected: function () { return false; },
        enabled: command_1.CommandConditions.hasPreviousView,
        invoke: function (dispatch, getState) {
            var mapName = getState().config.activeMapName;
            if (mapName) {
                dispatch((0, map_1.previousView)(mapName));
            }
        }
    });
    //Next View
    (0, command_1.registerCommand)(command_1.DefaultCommands.NextView, {
        iconClass: assets_1.SPRITE_VIEW_FORWARD,
        selected: function () { return false; },
        enabled: command_1.CommandConditions.hasNextView,
        invoke: function (dispatch, getState) {
            var mapName = getState().config.activeMapName;
            if (mapName) {
                dispatch((0, map_1.nextView)(mapName));
            }
        }
    });
    //Geolocation
    (0, command_1.registerCommand)(command_1.DefaultCommands.Geolocation, {
        iconClass: assets_1.SPRITE_GEOLOCATION,
        selected: function () { return false; },
        enabled: command_1.CommandConditions.isNotBusy,
        invoke: function (_dispatch, getState, viewer, parameters) {
            var state = getState();
            var view = (0, common_1.getCurrentView)(state);
            var rtMap = (0, common_1.getRuntimeMap)(state);
            var locale = state.config.locale;
            if (viewer && view && rtMap) {
                var fact_1 = viewer.getOLFactory();
                var geoOptions = {};
                var zoomScale_1 = view.scale;
                if (parameters.ZoomLevel) {
                    zoomScale_1 = parseInt(parameters.ZoomLevel, 10);
                }
                if (parameters.EnableHighAccuracy) {
                    geoOptions.enableHighAccuracy = (parameters.EnableHighAccuracy == "true");
                }
                if (parameters.Timeout) {
                    geoOptions.timeout = parseInt(parameters.Timeout, 10);
                }
                if (parameters.MaximumAge) {
                    geoOptions.maximumAge = parseInt(parameters.MaximumAge, 10);
                }
                navigator.geolocation.getCurrentPosition(function (pos) {
                    var proj = viewer.getProjection();
                    var txCoord = fact_1.transformCoordinateFromLonLat([pos.coords.longitude, pos.coords.latitude], proj);
                    var testCoord = fact_1.transformCoordinateFromLonLat([pos.coords.longitude, pos.coords.latitude], "EPSG:".concat(rtMap.CoordinateSystem.EpsgCode));
                    viewer.zoomToView(txCoord[0], txCoord[1], zoomScale_1);
                    var extents = [
                        rtMap.Extents.LowerLeftCoordinate.X,
                        rtMap.Extents.LowerLeftCoordinate.Y,
                        rtMap.Extents.UpperRightCoordinate.X,
                        rtMap.Extents.UpperRightCoordinate.Y
                    ];
                    if (fact_1.extentContainsXY(extents, testCoord[0], testCoord[1])) {
                        viewer.toastSuccess("geolocation", (0, i18n_1.tr)("GEOLOCATION_SUCCESS", locale));
                        //getTopToaster().show({ icon: "geolocation", message: tr("GEOLOCATION_SUCCESS", locale), intent: Intent.SUCCESS });
                    }
                    else {
                        viewer.toastWarning("warning-sign", (0, i18n_1.tr)("GEOLOCATION_WARN_OUTSIDE_MAP", locale));
                        //getTopToaster().show({ icon: "warning-sign", message: tr("GEOLOCATION_WARN_OUTSIDE_MAP", locale), intent: Intent.WARNING });
                    }
                }, function (err) {
                    viewer.toastError("error", (0, i18n_1.tr)("GEOLOCATION_ERROR", locale, { message: err.message, code: err.code }));
                    //getTopToaster().show({ icon: "error", message: tr("GEOLOCATION_ERROR", locale, { message: err.message, code: err.code }), intent: Intent.DANGER });
                }, geoOptions);
            }
        }
    });
    //Coordinate Tracker
    (0, command_1.registerCommand)(command_1.DefaultCommands.CoordinateTracker, {
        iconClass: assets_1.SPRITE_COORDINATE_TRACKER,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, getState, _viewer, parameters) {
            var config = getState().config;
            var url = "component://CoordinateTracker?".concat((parameters.Projection || []).map(function (p) { return "projections=" + p; }).join("&"));
            var cmdDef = buildTargetedCommand(config, parameters);
            (0, command_1.openUrlInTarget)(command_1.DefaultCommands.CoordinateTracker, cmdDef, config.capabilities.hasTaskPane, dispatch, url, (0, i18n_1.tr)("COORDTRACKER", config.locale));
        }
    });
    //External Layer Manager
    (0, command_1.registerCommand)(command_1.DefaultCommands.AddManageLayers, {
        iconClass: assets_1.SPRITE_LAYER_ADD,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (dispatch, getState, _viewer, parameters) {
            var config = getState().config;
            var url = "component://".concat(component_1.DefaultComponentNames.AddManageLayers);
            var cmdDef = buildTargetedCommand(config, parameters);
            (0, command_1.openUrlInTarget)(command_1.DefaultCommands.AddManageLayers, cmdDef, config.capabilities.hasTaskPane, dispatch, url, (0, i18n_1.tr)("ADD_MANAGE_LAYERS", config.locale));
        }
    });
    //Print
    (0, command_1.registerCommand)(command_1.DefaultCommands.Print, {
        iconClass: assets_1.SPRITE_PRINT,
        selected: function () { return false; },
        enabled: function () { return true; },
        invoke: function (_dispatch, _getState, viewer, _parameters) {
            viewer === null || viewer === void 0 ? void 0 : viewer.exportImage({
                callback: function (image) {
                    var el = react_1.default.createElement("img", { src: image });
                    var printWindow = window.open();
                    if (printWindow) {
                        // Open and immediately close the document. This works around a problem in Firefox that is
                        // captured here: https://bugzilla.mozilla.org/show_bug.cgi?id=667227.
                        // Essentially, when we first create an iframe, it has no document loaded and asynchronously
                        // starts a load of "about:blank". If we access the document object and start manipulating it
                        // before that async load completes, a new document will be automatically created. But then
                        // when the async load completes, the original, automatically-created document gets unloaded
                        // and the new "about:blank" gets swapped in. End result: everything we add to the DOM before
                        // the async load complete gets lost and Firefox ends up printing a blank page.
                        // Explicitly opening and then closing a new document _seems_ to avoid this.
                        printWindow.document.open();
                        printWindow.document.close();
                        printWindow.document.head.innerHTML = "\n                                <meta charset=\"UTF-8\">\n                                <title>Print View</title>\n                                ";
                        printWindow.document.body.innerHTML = '<div id="print"></div>';
                        react_dom_1.default.render(el, printWindow.document.getElementById("print"));
                    }
                }
            });
        }
    });
    //Fusion template helper commands
    /*
    registerCommand("showOverview", {
        icon: "images/icons/invoke-script",
        selected: () => false,
        enabled: CommandConditions.isNotBusy,
        invoke: (dispatch, getState, viewer, parameters) => {

        }
    });
    */
    (0, command_1.registerCommand)("showTaskPane", {
        iconClass: assets_1.SPRITE_INVOKE_SCRIPT,
        selected: function () { return false; },
        enabled: command_1.CommandConditions.isNotBusy,
        invoke: function (dispatch, _getState) {
            dispatch((0, template_1.setTaskPaneVisibility)(true));
        }
    });
    (0, command_1.registerCommand)("showLegend", {
        iconClass: assets_1.SPRITE_INVOKE_SCRIPT,
        selected: function () { return false; },
        enabled: command_1.CommandConditions.isNotBusy,
        invoke: function (dispatch, _getState) {
            dispatch((0, template_1.setLegendVisibility)(true));
        }
    });
    (0, command_1.registerCommand)("showSelectionPanel", {
        iconClass: assets_1.SPRITE_INVOKE_SCRIPT,
        selected: function () { return false; },
        enabled: command_1.CommandConditions.isNotBusy,
        invoke: function (dispatch, _getState) {
            dispatch((0, template_1.setSelectionPanelVisibility)(true));
        }
    });
}
exports.initDefaultCommands = initDefaultCommands;
//# sourceMappingURL=default-commands.js.map