import React, { useEffect, useState } from "react";
import { ToolbarSection } from "..";
import { FEAGlobals } from "../../../../common";
import "./bloomberg.css";
var ConnectionStatus;
(function (ConnectionStatus) {
    ConnectionStatus["disconnected"] = "Disconnected";
    ConnectionStatus["connected"] = "Connected";
    ConnectionStatus["error"] = "Error";
})(ConnectionStatus || (ConnectionStatus = {}));
/**
 * Returns the BloombergBridgeClient from FSBL.Clients (if it exists). Note that the client is only guaranteed
 * to be available if the Bloomberg Bridge service is running AND the React component is being rendered. That is
 * to say, the client may not be available outside of React components (i.e. top level).
 *
 * @returns The BloombergBridgeClient
 */
const getBBGClient = () => FEAGlobals.FSBL.Clients.BloombergBridgeClient;
export const BloombergStatusBadge = () => {
    // Set up the BloombergBridgeClient that will be used for all messaging to/from Bloomberg
    const bbg = getBBGClient();
    if (!bbg) {
        FEAGlobals.FSBL.Clients.Logger.log("BloombergBridgeClient not found in FSBL.Clients");
        // Do not render the component if BloombergBridgeClient is not available
        return React.createElement(React.Fragment, null);
    }
    const [connectionStatus, setConnectionStatus] = useState(ConnectionStatus.disconnected);
    const [errorMessage, setErrorMessage] = useState("");
    useEffect(() => {
        const checkConnection = () => {
            bbg.checkConnection((err, response) => {
                if (!err && response === true) {
                    setConnectionStatus(ConnectionStatus.connected);
                    setErrorMessage("");
                }
                else if (err) {
                    FEAGlobals.FSBL.Clients.Logger.debug("Error received when checking connection", err);
                    setConnectionStatus(ConnectionStatus.error);
                    setErrorMessage("Confirm Bloomberg and Bridge are both running.");
                }
                else {
                    FEAGlobals.FSBL.Clients.Logger.debug("Negative response when checking connection: ", response);
                    setConnectionStatus(ConnectionStatus.disconnected);
                    setErrorMessage("");
                }
            });
        };
        try {
            //do the initial check
            checkConnection();
            //listen for connection events (listen/transmit)
            bbg.setConnectionEventListener(checkConnection);
            // its also possible to poll for connection status,
            //  worth doing in case the bridge process is killed off and doesn't get a chance to send an update
            setInterval(checkConnection, 30000);
        }
        catch (e) {
            FEAGlobals.FSBL.Clients.Logger.debug(`Error in bbg prefs: ${e}`);
        }
    }, []);
    return (React.createElement("div", { className: "connectionStatusBar", tabIndex: 0, role: "button", title: `${connectionStatus} ${errorMessage}`, "aria-label": `${connectionStatus} ${errorMessage}` },
        React.createElement("span", { className: `connectionStatus status-${connectionStatus}` }),
        "Bloomberg"));
};
// eslint-disable-next-line sonarjs/cognitive-complexity
export const BloombergStatus = () => {
    // Set up the BloombergBridgeClient that will be used for all messaging to/from Bloomberg
    const bbg = getBBGClient();
    if (!bbg) {
        FEAGlobals.FSBL.Clients.Logger.log("BloombergBridgeClient not found in FSBL.Clients");
        // Do not render the component if BloombergBridgeClient is not available
        return React.createElement(React.Fragment, null);
    }
    const [bloombergEnabled, setBloombergEnabled] = useState(false);
    const [showBloomberg, setShowBloomberg] = useState(false);
    useEffect(() => {
        async function fetchBloomberg() {
            const { err, data: showStatus } = await FEAGlobals.FSBL.Clients.ConfigClient.get([
                "finsemble",
                "custom",
                "bloomberg",
                "showStatus",
            ]);
            if (err) {
                FEAGlobals.FSBL.Clients.Logger.debug(`Could not determine Bloomberg show status: ${err}`);
            }
            if (showStatus) {
                setShowBloomberg(true);
                setBloombergEnabled(true);
            }
            else {
                setShowBloomberg(false);
                setBloombergEnabled(false);
            }
        }
        fetchBloomberg();
        let statusHandler = (err, status) => {
            if (!status)
                return;
            if (err) {
                FEAGlobals.FSBL.Clients.Logger.debug("Error received when checking bloomberg bridge config", err);
            }
            else {
                let bbgShowStatus = !!(typeof status.value == "undefined" || status.value);
                setShowBloomberg(bbgShowStatus);
            }
        };
        FEAGlobals.FSBL.Clients.ConfigClient.get(["finsemble", "custom", "bloomberg", "showStatus"], statusHandler);
        FEAGlobals.FSBL.Clients.ConfigClient.addListener({ field: "finsemble.custom.bloomberg.showStatus" }, statusHandler);
        let enabledStatusHandler = (err, status) => {
            if (!status)
                return;
            if (err) {
                FEAGlobals.FSBL.Clients.Logger.debug("Error received when checking bloomberg bridge config", err);
            }
            else {
                let isBloombergEnabled = !!(typeof status.value == "undefined" || status.value);
                setBloombergEnabled(isBloombergEnabled);
            }
        };
        FEAGlobals.FSBL.Clients.ConfigClient.get(["finsemble", "custom", "bloomberg", "enabled"], enabledStatusHandler);
        FEAGlobals.FSBL.Clients.ConfigClient.addListener({ field: "finsemble.custom.bloomberg.enabled" }, enabledStatusHandler);
    }, []);
    const bbgStatus = (React.createElement(ToolbarSection, { className: "right" },
        React.createElement("div", { className: "divider" }),
        React.createElement(BloombergStatusBadge, null)));
    return showBloomberg && bloombergEnabled ? bbgStatus : React.createElement(React.Fragment, null);
};
//# sourceMappingURL=BloombergStatus.js.map