/*!
 * Copyright 2017 by ChartIQ, Inc.
 * All rights reserved.
 */
import React, { useState } from "react";
import { reduxContext, useDispatch } from "../FinsembleProvider";
import { Provider } from "react-redux";
import { ResolverDialog } from "./ResolverDialog";
import { FEAGlobals } from "../../../common/Globals";
import { useTitle } from "../../hooks/useTitle";
import { getRemoteStore } from "../../../common/redux/getRemoteStore";
import { emptyStore } from "../../../platform/services/window/modules/actions";
import { actions } from "../../../platform/services/window/modules/actions";
import { useFloatingFocus } from "../../hooks/useFloatingFocus";
/**
 * Scrim management is handled by the "ux" slice of the window service's redux store.
 */
export const getStore = () => getRemoteStore({ server: "@@finsemble/remoteRedux/WindowServiceStore", slice: "ux", emptyStore });
let windowIdentifier = null;
export const ResolverContainer = () => {
    const dispatch = useDispatch();
    const [firstLoad, setFirstLoad] = useState(true);
    const [intentRaiser, setIntentRaiser] = useState("");
    const [sendCallback, setSendCallback] = useState(() => { });
    const [cancelCallback, setCancelCallback] = useState(() => { });
    const [resolutionList, setResolutionList] = useState([]);
    const [showRememberCheckbox, setShowRememberCheckbox] = useState(false);
    useFloatingFocus();
    useTitle("Resolver");
    const hideScrim = () => {
        // @ts-ignore
        dispatch(actions.hideScrim());
    };
    const reset = () => {
        hideScrim();
        FEAGlobals.finsembleWindow.hide();
        setIntentRaiser("");
        setResolutionList([]);
    };
    const handleChoices = async (choices) => {
        var _a;
        setIntentRaiser((_a = choices.originatingAppName) !== null && _a !== void 0 ? _a : "");
        setResolutionList(choices.resolutionList);
        if (windowIdentifier && choices.originatingAppWindow) {
            FEAGlobals.FSBL.Clients.LauncherClient.showWindow(windowIdentifier, {
                position: "relative",
                relativeWindow: { windowName: choices.originatingAppWindow },
                top: "center",
                left: "center",
            });
        }
        else {
            FEAGlobals.finsembleWindow.show();
        }
        FEAGlobals.finsembleWindow.focus();
    };
    // We want to register as an IntentResolverListener, but we only want to register once
    // However, the IntentResolverListener handler needs to have access to this component's states
    // So, this block will register the listener, and then never be called again
    if (firstLoad) {
        setFirstLoad(false);
        FEAGlobals.FSBL.Clients.ConfigClient.get(["finsemble", "servicesConfig", "interop", "allowResolverToRemember"], (err, response) => {
            setShowRememberCheckbox(response !== undefined ? response : true);
        });
        FEAGlobals.FSBL.Clients.LauncherClient.getMyWindowIdentifier((win) => {
            windowIdentifier = win;
        });
        // Catches alt-tab and other actions that take focus away from the window
        window.addEventListener("blur", () => {
            hideScrim();
        });
        // Sets up the response handlers which send choices, or cancellations, back to the interop service.
        // It is the act of resolving or rejecting which sends the choice/cancellation back to the interop service.
        // Note that the second parameter to setState() takes a double function to avoid reductive functional updates
        // https://reactjs.org/docs/hooks-reference.html#functional-updates
        const intentResolverHandler = (choices) => new Promise((resolve, reject) => {
            handleChoices(choices);
            setSendCallback(() => (result) => {
                reset();
                // originatingAppName and originatingAppWindow returned to support auto-associate
                result.originatingAppName = choices.originatingAppName;
                result.originatingAppWindow = choices.originatingAppWindow;
                resolve(result);
            });
            setCancelCallback(() => () => {
                reset();
                reject({ err: "Cancelled by user" });
            });
        });
        FEAGlobals.FSBL.internal.interopAdmin.registerUIResolverListener(intentResolverHandler).then(() => { });
        reset();
    }
    return (React.createElement(Provider, { context: reduxContext, store: getStore() },
        React.createElement(ResolverDialog, { intentRaiser: intentRaiser, resolutionList: resolutionList, onSend: (selected) => {
                FEAGlobals.FSBL.Clients.Logger.system.log(`tag:FDC3:raiseIntent UI Resolver selected for intent`, selected);
                sendCallback(selected);
            }, onCancel: cancelCallback, showRememberCheckbox: showRememberCheckbox })));
};
//# sourceMappingURL=ResolverContainer.js.map