/*!
 * Copyright 2017 by ChartIQ, Inc.
 * All rights reserved.
 */
import React, { useRef, useEffect, useState } from "react";
import { LinkerGroups } from "./LinkerGroups";
import { useDispatch, useSelector, Provider } from "react-redux";
import { getStore } from "../linker/remoteRedux";
import { LinkerButtonDeprecated } from "./LinkerButtonDeprecated";
import { linkerActions as actions } from "../../../platform/services/Interop/modules/actions";
import { FEAGlobals } from "../../../common/Globals";
const LinkerButtonIcon = () => (React.createElement("svg", { width: "15px", height: "15px", viewBox: "2 1 13 13", xmlns: "http://www.w3.org/2000/svg", xmlnsXlink: "http://www.w3.org/1999/xlink" },
    React.createElement("title", null, "Linker"),
    React.createElement("defs", null,
        React.createElement("path", { id: "prefix__b", d: "M17.925 15.425h-1v-2.5a2.5 2.5 0 0 0-5 0v2.5h-1v-2.5a3.5 3.5 0 1 1 7 0v2.5zm0 2v2.5a3.5 3.5 0 1 1-7 0v-2.5h1v2.5a2.5 2.5 0 0 0 5 0v-2.5h1zm-3.5-4a.5.5 0 0 1 .5.5v5a.5.5 0 0 1-1 0v-5a.5.5 0 0 1 .5-.5z" }),
        React.createElement("filter", { id: "prefix__a", x: "-28.6%", y: "-7.1%", width: "157.1%", height: "128.6%" },
            React.createElement("feOffset", { dy: "1", in: "SourceAlpha", result: "shadowOffsetOuter1" }),
            React.createElement("feGaussianBlur", { in: "shadowOffsetOuter1", result: "shadowBlurOuter1", stdDeviation: ".5" }),
            React.createElement("feColorMatrix", { in: "shadowBlurOuter1", values: "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0" }))),
    React.createElement("g", { transform: "rotate(45 22.289 4.682)", fillRule: "nonzero", fill: "none" },
        React.createElement("use", { filter: "url(#prefix__a)", xlinkHref: "#prefix__b" }),
        React.createElement("use", { xlinkHref: "#prefix__b" }))));
const LinkerButtonRedux = ({ enableKeyboardShortcut = true }) => {
    const dispatch = useDispatch();
    const state = useSelector((currentState) => currentState);
    const buttonRef = useRef(null);
    const [shouldShowLinkerWindow, setShouldShowLinkerWindow] = useState(false);
    // updates the global LinkerStore
    const showLinkerWindow = () => {
        // These action creators can now be imported from finsemble-core
        dispatch(actions.setActiveWindow({
            type: "linker/setActiveWindow",
            payload: {
                windowName: FEAGlobals.finsembleWindow.name,
            },
        }));
        setShouldShowLinkerWindow(true);
    };
    // show linker window after the state has been updated
    useEffect(() => {
        var _a, _b, _c;
        if (state.activeWindowName === FEAGlobals.finsembleWindow.name && shouldShowLinkerWindow) {
            // The offset parent is needed so that the menu isn't shown relative to the icon.
            // The HTMLElement.offsetParent read-only property returns a reference to the object which is the closest (nearest in the containment hierarchy) positioned containing element.
            // Necessary to cast because refs are type "Element" (which could be an SVGElement...)
            const linkerButton = buttonRef.current;
            if (linkerButton) {
                const linkerButtonDiv = linkerButton;
                const linkerParent = ((_a = linkerButtonDiv.offsetParent) !== null && _a !== void 0 ? _a : linkerButtonDiv.parentElement);
                const params = {
                    position: "relative",
                    left: (_b = linkerParent === null || linkerParent === void 0 ? void 0 : linkerParent.offsetLeft) !== null && _b !== void 0 ? _b : 0,
                    top: (_c = linkerParent === null || linkerParent === void 0 ? void 0 : linkerParent.offsetHeight) !== null && _c !== void 0 ? _c : 0,
                    forceOntoMonitor: true,
                    spawnIfNotFound: false,
                };
                const wi = {
                    componentType: "linkerWindow",
                };
                FEAGlobals.FSBL.Clients.LauncherClient.toggleWindowOnClick(linkerButtonDiv, wi, params);
                setShouldShowLinkerWindow(false);
            }
        }
    }, [state, shouldShowLinkerWindow]);
    // If this window is in the list of linker clients then display this button
    const displayMe = state.clients[FEAGlobals.finsembleWindow.name] !== undefined;
    useEffect(() => {
        enableKeyboardShortcut &&
            window.addEventListener("keydown", (e) => {
                if (e.key === "l" && (e.ctrlKey || e.metaKey)) {
                    showLinkerWindow();
                }
            });
    }, []);
    return (React.createElement(React.Fragment, null, displayMe && (React.createElement("div", { ref: buttonRef, title: "Link Data", className: "linkerSection" },
        React.createElement("div", { className: "fsbl-icon fsbl-linker", onClick: showLinkerWindow },
            React.createElement(LinkerButtonIcon, null)),
        React.createElement(LinkerGroups, null)))));
};
/**
 * Picks whether to display the current or deprecated LinkerElement.
 * If config `finsemble.servicesConfig.linker.enabled` is set to true then the deprecated version will be used.
 *
 * This code should be removed once the linkerClient is removed from Finsemble.
 */
const WhichLinker = ({ enableKeyboardShortcut }) => {
    const [whichLinker, setWhichLinker] = React.useState("");
    // the flag to indicate that component is mounted and the state could be updated without React warnings.
    let isMounted = false;
    useEffect(() => {
        // sets the flag when the useEffect is first called.
        isMounted = true;
        (async () => {
            const { data } = await FEAGlobals.FSBL.Clients.ConfigClient.get([
                "finsemble",
                "servicesConfig",
                "linker",
                "enabled",
            ]);
            // The async call above could be finished after the component will be unmounted.
            // Checks and updates the state only for mounted component.
            if (isMounted) {
                const theLinker = data ? "LinkerElementDeprecated" : "LinkerElement";
                setWhichLinker(theLinker);
            }
        })();
        return () => {
            isMounted = false;
        };
    }, []);
    return (React.createElement(React.Fragment, null,
        whichLinker === "LinkerElement" && (React.createElement(Provider, { store: getStore() },
            React.createElement(LinkerButtonRedux, { enableKeyboardShortcut: enableKeyboardShortcut }))),
        whichLinker === "LinkerElementDeprecated" && React.createElement(LinkerButtonDeprecated, null)));
};
export const LinkerButton = ({ enableKeyboardShortcut = true }) => (React.createElement(WhichLinker, { enableKeyboardShortcut: enableKeyboardShortcut }));
//# sourceMappingURL=LinkerButton.js.map