"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuickPlotContainer = void 0;
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var runtime_1 = require("../api/runtime");
var i18n_1 = require("../api/i18n");
var common_1 = require("../api/common");
var map_capturer_context_1 = require("./map-capturer-context");
var core_1 = require("@blueprintjs/core");
var hooks_1 = require("./hooks");
var map_1 = require("../actions/map");
var logger_1 = require("../utils/logger");
var hooks_mapguide_1 = require("./hooks-mapguide");
var context_1 = require("../components/map-providers/context");
function getMargin() {
    /*
    var widget = getParent().Fusion.getWidgetsByType("QuickPlot")[0];
    var margin;
    
    if(!!widget.margin){
         margin = widget.margin;
    }else{
        //the default margin
        margin = {top: 25.4, buttom: 12.7, left: 12.7, right: 12.7};
    }
    return margin;
    */
    return { top: 25.4, buttom: 12.7, left: 12.7, right: 12.7 };
}
function getPrintSize(viewer, showAdvanced, paperSize, orientation) {
    var value = paperSize.split(",");
    var size;
    if (orientation === "P") {
        size = { w: parseFloat(value[0]), h: parseFloat(value[1]) };
    }
    else {
        size = { w: parseFloat(value[1]), h: parseFloat(value[0]) };
    }
    if (!showAdvanced) {
        // Calculate the paper size to make sure it has a same ratio with the viweport
        var paperRatio = size.w / size.h;
        var viewSize = viewer.getSize();
        var vs = void 0;
        if (orientation === "P") {
            vs = {
                w: viewSize[1],
                h: viewSize[0]
            };
        }
        else {
            vs = {
                w: viewSize[0],
                h: viewSize[1]
            };
        }
        if (vs) {
            var viewRatio = vs.w / vs.h;
            if (paperRatio > viewRatio) {
                size.w = size.h * viewRatio;
            }
            else {
                size.h = size.w / viewRatio;
            }
        }
    }
    var margins = getMargin();
    size.h = size.h - margins.top - margins.buttom;
    size.w = size.w - margins.left - margins.right;
    return size;
}
var _mapCapturers = [];
function getActiveCapturer(viewer, mapNames, activeMapName) {
    var activeCapturer;
    if (_mapCapturers.length == 0) {
        if (mapNames.length) {
            for (var _i = 0, mapNames_1 = mapNames; _i < mapNames_1.length; _i++) {
                var mapName = mapNames_1[_i];
                var context = new map_capturer_context_1.MapCapturerContext(viewer, mapName);
                _mapCapturers.push(context);
                if (activeMapName == mapName) {
                    activeCapturer = context;
                }
            }
        }
    }
    else {
        activeCapturer = _mapCapturers.filter(function (m) { return m.getMapName() === activeMapName; })[0];
    }
    return activeCapturer;
}
function toggleMapCapturerLayer(locale, mapNames, activeMapName, showAdvanced, paperSize, orientation, scale, rotation, updateBoxCoords, setViewRotationEnabled, setViewRotation) {
    var bVisible = showAdvanced;
    var viewer = (0, runtime_1.getViewer)();
    if (viewer && mapNames) {
        var activeCapturer = getActiveCapturer(viewer, mapNames, activeMapName);
        if (activeCapturer) {
            if (bVisible) {
                var ppSize = getPrintSize(viewer, showAdvanced, paperSize, orientation);
                var cb = {
                    updateBoxCoords: updateBoxCoords
                };
                activeCapturer.activate(cb, ppSize, parseFloat(scale), rotation);
                //For simplicity, reset rotation to 0 and prevent the ability to rotate while the map capture box
                //is active
                setViewRotationEnabled(false);
                setViewRotation(0);
                viewer.toastPrimary("info-sign", (0, i18n_1.tr)("QUICKPLOT_BOX_INFO", locale));
            }
            else {
                activeCapturer.deactivate();
                setViewRotationEnabled(true);
            }
        }
    }
}
var QuickPlotContainer = function () {
    var _a, _b;
    var _c = React.useState(""), title = _c[0], setTitle = _c[1];
    "";
    var _d = React.useState(""), subTitle = _d[0], setSubTitle = _d[1];
    var _e = React.useState(false), showLegend = _e[0], setShowLegend = _e[1];
    var _f = React.useState(false), showNorthBar = _f[0], setShowNorthBar = _f[1];
    var _g = React.useState(false), showCoordinates = _g[0], setShowCoordinates = _g[1];
    var _h = React.useState(false), showScaleBar = _h[0], setShowScaleBar = _h[1];
    var _j = React.useState(false), showDisclaimer = _j[0], setShowDisclaimer = _j[1];
    var _k = React.useState(false), showAdvanced = _k[0], setShowAdvanced = _k[1];
    var _l = React.useState("P"), orientation = _l[0], setOrientation = _l[1];
    var _m = React.useState("210.0,297.0,A4"), paperSize = _m[0], setPaperSize = _m[1];
    var _o = React.useState("5000"), scale = _o[0], setScale = _o[1];
    var _p = React.useState("96"), dpi = _p[0], setDpi = _p[1];
    var _q = React.useState(0), rotation = _q[0], setRotation = _q[1];
    var _r = React.useState(""), box = _r[0], setBox = _r[1];
    var _s = React.useState(""), normalizedBox = _s[0], setNormalizedBox = _s[1];
    var locale = (0, hooks_1.useViewerLocale)();
    var activeMapName = (0, hooks_1.useActiveMapName)();
    var mapNames = (_a = (0, hooks_1.useAvailableMaps)()) === null || _a === void 0 ? void 0 : _a.map(function (m) { return m.value; });
    var map = (0, hooks_mapguide_1.useActiveMapState)();
    var view = (0, hooks_1.useActiveMapView)();
    var externalBaseLayers = (_b = (0, hooks_1.useActiveMapExternalBaseLayers)()) === null || _b === void 0 ? void 0 : _b.filter(function (ebl) { return (0, common_1.isVisualBaseLayer)(ebl); });
    var dispatch = (0, context_1.useReduxDispatch)();
    var setViewRotationAction = function (rotation) { return dispatch((0, map_1.setViewRotation)(rotation)); };
    var setViewRotationEnabledAction = function (enabled) { return dispatch((0, map_1.setViewRotationEnabled)(enabled)); };
    var onTitleChanged = function (e) {
        setTitle(e.target.value);
    };
    var onSubTitleChanged = function (e) {
        setSubTitle(e.target.value);
    };
    var onShowLegendChanged = function () {
        setShowLegend(!showLegend);
    };
    var onShowNorthArrowChanged = function () {
        setShowNorthBar(!showNorthBar);
    };
    var onShowCoordinatesChanged = function () {
        setShowCoordinates(!showCoordinates);
    };
    var onShowScaleBarChanged = function () {
        setShowScaleBar(!showScaleBar);
    };
    var onShowDisclaimerChanged = function () {
        setShowDisclaimer(!showDisclaimer);
    };
    var onDpiChanged = function (e) {
        setDpi(e.target.value);
    };
    var onAdvancedOptionsChanged = function () {
        setShowAdvanced(!showAdvanced);
    };
    var onScaleChanged = function (e) {
        setScale(e.target.value);
    };
    var onPaperSizeChanged = function (e) {
        setPaperSize(e.target.value);
    };
    var onOrientationChanged = function (e) {
        setOrientation(e.target.value);
    };
    var onRotationChanged = function (value) {
        setRotation(value);
    };
    var onGeneratePlot = function () { };
    var updateBoxCoords = function (box, normalizedBox) {
        setBox(box);
        setNormalizedBox(normalizedBox);
    };
    //Side-effect that emulates the old componentWillUnmount lifecyle method to tear down
    //the active map capturer
    React.useEffect(function () {
        return function () {
            //Tear down all active capture box layers
            var viewer = (0, runtime_1.getViewer)();
            if (viewer && mapNames) {
                for (var _i = 0, mapNames_2 = mapNames; _i < mapNames_2.length; _i++) {
                    var activeMapName_1 = mapNames_2[_i];
                    var activeCapturer = getActiveCapturer(viewer, mapNames, activeMapName_1);
                    if (activeCapturer) {
                        (0, logger_1.debug)("De-activating map capturer for: ".concat(activeMapName_1));
                        activeCapturer.deactivate();
                    }
                }
            }
        };
    }, []);
    //Although the dep array arg of React.useEffect() has effectively rendered the need to
    //track previous values obsolete, we still need to track the previous advanced flag to
    //verify that the flag is amongst the actual values in the dep array that has changed
    var prevShowAdvanced = (0, hooks_1.usePrevious)(showAdvanced);
    //Side-effect that toggles/updates associated map capturers
    React.useEffect(function () {
        if (activeMapName && mapNames) {
            if (showAdvanced != prevShowAdvanced) {
                toggleMapCapturerLayer(locale, mapNames, activeMapName, showAdvanced, paperSize, orientation, scale, rotation, updateBoxCoords, setViewRotationEnabledAction, setViewRotationAction);
            }
            if (showAdvanced) {
                var v = (0, runtime_1.getViewer)();
                if (v) {
                    var capturer = getActiveCapturer(v, mapNames, activeMapName);
                    if (capturer) {
                        var ppSize_1 = getPrintSize(v, showAdvanced, paperSize, orientation);
                        (0, logger_1.debug)("Updating map capturer for: ".concat(activeMapName));
                        capturer.updateBox(ppSize_1, parseFloat(scale), rotation);
                    }
                }
            }
        }
    }, [mapNames, activeMapName, showAdvanced, scale, paperSize, orientation, rotation, locale]);
    var viewer = (0, runtime_1.getViewer)();
    if (!viewer || !map || !view) {
        return React.createElement("noscript", null);
    }
    var hasExternalBaseLayers = false;
    if (externalBaseLayers) {
        hasExternalBaseLayers = externalBaseLayers.length > 0;
    }
    var normBox = normalizedBox;
    var theBox = box;
    if (!showAdvanced) {
        var extent = viewer.getCurrentExtent();
        theBox = "".concat(extent[0], ", ").concat(extent[1], ", ").concat(extent[2], ", ").concat(extent[1], ", ").concat(extent[2], ", ").concat(extent[3], ", ").concat(extent[0], ", ").concat(extent[3], ", ").concat(extent[0], ", ").concat(extent[1]);
        normBox = theBox;
    }
    var ppSize;
    var prSize;
    var tokens = paperSize.split(",");
    if (orientation === "L") {
        prSize = "".concat(tokens[1], ",").concat(tokens[0]);
        ppSize = "".concat(prSize, ",").concat(tokens[2]);
    }
    else { // P
        prSize = "".concat(tokens[0], ",").concat(tokens[1]);
        ppSize = "".concat(prSize, ",").concat(tokens[2]);
    }
    var url = "".concat((0, runtime_1.getFusionRoot)(), "/widgets/QuickPlot/PlotAsPDF.php");
    return React.createElement("div", { className: "component-quick-plot" },
        React.createElement("form", { id: "Form1", name: "Form1", target: "_blank", method: "post", action: url },
            React.createElement("input", { type: "hidden", id: "printId", name: "printId", value: "".concat(Math.random() * 1000) }),
            React.createElement("div", { className: "Title FixWidth" }, (0, i18n_1.tr)("QUICKPLOT_HEADER", locale)),
            React.createElement("label", { className: "bp3-label" },
                (0, i18n_1.tr)("QUICKPLOT_TITLE", locale),
                React.createElement("input", { type: "text", className: "bp3-input bp3-fill", dir: "auto", name: "{field:title}", id: "title", maxLength: 100, value: title, onChange: onTitleChanged })),
            React.createElement("label", { className: "bp3-label" },
                (0, i18n_1.tr)("QUICKPLOT_SUBTITLE", locale),
                React.createElement("input", { type: "text", className: "bp3-input bp3-fill", dir: "auto", name: "{field:sub_title}", id: "subtitle", maxLength: 100, value: subTitle, onChange: onSubTitleChanged })),
            React.createElement("label", { className: "bp3-label" },
                (0, i18n_1.tr)("QUICKPLOT_PAPER_SIZE", locale),
                React.createElement("div", { className: "bp3-select bp3-fill" },
                    React.createElement(core_1.HTMLSelect, { className: "FixWidth", id: "paperSizeSelect", name: "paperSizeSelect", value: paperSize, onChange: onPaperSizeChanged },
                        React.createElement("option", { value: "210.0,297.0,A4" }, "A4 (210x297 mm; 8.27x11.69 In) "),
                        React.createElement("option", { value: "297.0,420.0,A3" }, "A3 (297x420 mm; 11.69x16.54 In) "),
                        React.createElement("option", { value: "148.0,210.0,A5" }, "A5 (148x210 mm; 5.83x8.27 in) "),
                        React.createElement("option", { value: "216.0,279.0,Letter" }, "Letter (216x279 mm; 8.50x11.00 In) "),
                        React.createElement("option", { value: "216.0,356.0,Legal" }, "Legal (216x356 mm; 8.50x14.00 In) ")))),
            React.createElement("label", { className: "bp3-label" },
                (0, i18n_1.tr)("QUICKPLOT_ORIENTATION", locale),
                React.createElement("div", { className: "bp3-select bp3-fill" },
                    React.createElement(core_1.HTMLSelect, { className: "FixWidth", id: "orientation", name: "orientation", value: orientation, onChange: onOrientationChanged },
                        React.createElement("option", { value: "P" }, (0, i18n_1.tr)("QUICKPLOT_ORIENTATION_P", locale)),
                        React.createElement("option", { value: "L" }, (0, i18n_1.tr)("QUICKPLOT_ORIENTATION_L", locale))))),
            React.createElement("input", { type: "hidden", id: "paperSize", name: "paperSize", value: ppSize }),
            React.createElement("input", { type: "hidden", id: "printSize", name: "printSize", value: prSize }),
            React.createElement("fieldset", null,
                React.createElement("legend", null, (0, i18n_1.tr)("QUICKPLOT_SHOWELEMENTS", locale)),
                React.createElement("label", { className: "bp3-control bp3-checkbox" },
                    React.createElement("input", { type: "checkbox", id: "ShowLegendCheckBox", name: "ShowLegend", checked: showLegend, onChange: onShowLegendChanged }),
                    React.createElement("span", { className: "bp3-control-indicator" }),
                    (0, i18n_1.tr)("QUICKPLOT_SHOWLEGEND", locale)),
                React.createElement("label", { className: "bp3-control bp3-checkbox" },
                    React.createElement("input", { type: "checkbox", id: "ShowNorthArrowCheckBox", name: "ShowNorthArrow", checked: showNorthBar, onChange: onShowNorthArrowChanged }),
                    React.createElement("span", { className: "bp3-control-indicator" }),
                    (0, i18n_1.tr)("QUICKPLOT_SHOWNORTHARROW", locale)),
                React.createElement("label", { className: "bp3-control bp3-checkbox" },
                    React.createElement("input", { type: "checkbox", id: "ShowCoordinatesCheckBox", name: "ShowCoordinates", checked: showCoordinates, onChange: onShowCoordinatesChanged }),
                    React.createElement("span", { className: "bp3-control-indicator" }),
                    (0, i18n_1.tr)("QUICKPLOT_SHOWCOORDINTES", locale)),
                React.createElement("label", { className: "bp3-control bp3-checkbox" },
                    React.createElement("input", { type: "checkbox", id: "ShowScaleBarCheckBox", name: "ShowScaleBar", checked: showScaleBar, onChange: onShowScaleBarChanged }),
                    React.createElement("span", { className: "bp3-control-indicator" }),
                    (0, i18n_1.tr)("QUICKPLOT_SHOWSCALEBAR", locale)),
                React.createElement("label", { className: "bp3-control bp3-checkbox" },
                    React.createElement("input", { type: "checkbox", id: "ShowDisclaimerCheckBox", name: "ShowDisclaimer", checked: showDisclaimer, onChange: onShowDisclaimerChanged }),
                    React.createElement("span", { className: "bp3-control-indicator" }),
                    (0, i18n_1.tr)("QUICKPLOT_SHOWDISCLAIMER", locale))),
            React.createElement("div", { className: "HPlaceholder5px" }),
            React.createElement("div", null,
                React.createElement("label", { className: "bp3-control bp3-checkbox" },
                    React.createElement("input", { type: "checkbox", id: "AdvancedOptionsCheckBox", onChange: onAdvancedOptionsChanged }),
                    React.createElement("span", { className: "bp3-control-indicator" }),
                    (0, i18n_1.tr)("QUICKPLOT_ADVANCED_OPTIONS", locale))),
            (function () {
                if (showAdvanced) {
                    return React.createElement("div", null,
                        React.createElement("label", { className: "bp3-label" },
                            (0, i18n_1.tr)("QUICKPLOT_SCALING", locale),
                            React.createElement("div", { className: "bp3-select bp3-fill" },
                                React.createElement(core_1.HTMLSelect, { className: "FixWidth", id: "scaleDenominator", name: "scaleDenominator", value: scale, onChange: onScaleChanged },
                                    React.createElement("option", { value: "500" }, "1: 500"),
                                    React.createElement("option", { value: "1000" }, "1: 1000"),
                                    React.createElement("option", { value: "2500" }, "1: 2500"),
                                    React.createElement("option", { value: "5000" }, "1: 5000")))),
                        React.createElement("label", { className: "bp3-label" },
                            (0, i18n_1.tr)("QUICKPLOT_DPI", locale),
                            React.createElement("div", { className: "bp3-select bp3-fill" },
                                React.createElement(core_1.HTMLSelect, { className: "FixWidth", id: "dpi", name: "dpi", value: dpi, onChange: onDpiChanged },
                                    React.createElement("option", { value: "96" }, "96"),
                                    React.createElement("option", { value: "150" }, "150"),
                                    React.createElement("option", { value: "300" }, "300"),
                                    React.createElement("option", { value: "600" }, "600")))),
                        React.createElement("label", { className: "bp3-label noselect" },
                            (0, i18n_1.tr)("QUICKPLOT_BOX_ROTATION", locale),
                            React.createElement("div", { style: { paddingLeft: 16, paddingRight: 16 } },
                                React.createElement(core_1.Slider, { min: 0, max: 360, labelStepSize: 90, stepSize: 1, value: rotation, onChange: onRotationChanged }))));
                }
                else {
                    return React.createElement("div", null,
                        React.createElement("input", { type: "hidden", id: "scaleDenominator", name: "scaleDenominator", value: "".concat(view.scale) }),
                        React.createElement("input", { type: "hidden", id: "dpi", name: "dpi", value: dpi }));
                }
            })(),
            React.createElement("div", { className: "HPlaceholder5px" }),
            (function () {
                if (hasExternalBaseLayers) {
                    return React.createElement(core_1.Callout, { intent: core_1.Intent.PRIMARY, icon: "info-sign" }, (0, i18n_1.tr)("QUICKPLOT_COMMERCIAL_LAYER_WARNING", locale));
                }
            })(),
            React.createElement("div", { className: "ButtonContainer FixWidth" },
                React.createElement(core_1.Button, { type: "submit", intent: core_1.Intent.PRIMARY, icon: "print", onClick: onGeneratePlot }, (0, i18n_1.tr)("QUICKPLOT_GENERATE", locale))),
            React.createElement("input", { type: "hidden", id: "margin", name: "margin" }),
            React.createElement("input", { type: "hidden", id: "normalizedBox", name: "normalizedBox", value: normBox }),
            React.createElement("input", { type: "hidden", id: "rotation", name: "rotation", value: -(rotation || 0) }),
            React.createElement("input", { type: "hidden", id: "sessionId", name: "sessionId", value: map.SessionId }),
            React.createElement("input", { type: "hidden", id: "mapName", name: "mapName", value: map.Name }),
            React.createElement("input", { type: "hidden", id: "box", name: "box", value: theBox }),
            React.createElement("input", { type: "hidden", id: "legalNotice", name: "legalNotice" })));
};
exports.QuickPlotContainer = QuickPlotContainer;
//# sourceMappingURL=quick-plot.js.map