import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { SPACE_PANEL_STATE } from "../../utils/utils";
import { selectIsCloudEnabled, selectIsUsingGlobalRegistry, selectRegistry, selectSpacePanelIsActive, } from "../../domains/global/selectors";
import { setSpacePanelStatusAction } from "../../domains/global/actions";
import { naturalSortCompare } from "../../domains/dashboard/utils/sorting";
import { SpacePanelIframe } from "./space-panel-iframe";
import { VisitedNodes } from "./components/visited-nodes";
import { ReplicatedNodes } from "./components/replicated-nodes";
import * as S from "./styled";
import noNetwork from "./no-network.svg";
const getStreamedNodes = (chartsMetadata) => {
    // decodeURI, because pathname (which is hostname) can contain white-spaces
    // or other characters which are URIencoded when user clicks the link
    // and we need to match it with `chartsMetadata.hostname`
    let base = document.location.origin.toString() + decodeURI(document.location.pathname.toString());
    if (base.endsWith(`/host/${chartsMetadata.hostname}/`)) {
        base = base.substring(0, base.length - (`/host/${chartsMetadata.hostname}/`).toString().length);
    }
    if (base.endsWith("/")) {
        base = base.substring(0, base.length - 1);
    }
    const masterNodeName = chartsMetadata.hosts[0].hostname;
    const masterNodeUrl = `${base}/`;
    const getUrl = (hostname) => `${base}/host/${hostname}/`;
    const streamedHosts = chartsMetadata.hosts.slice(1)
        .sort((a, b) => naturalSortCompare(a.hostname, b.hostname))
        .map(({ hostname }) => ({ hostname, url: getUrl(hostname) }));
    return {
        masterNodeName,
        masterNodeUrl,
        streamedHosts,
    };
};
export const SpacePanel = ({ chartsMetadata, cloudBaseURL, hasSignInHistory, isOffline, isSignedIn, signInUrl, }) => {
    var _a;
    const dispatch = useDispatch();
    const panelIsActive = useSelector(selectSpacePanelIsActive);
    useEffect(() => {
        const spacePanelStatePersisted = localStorage.getItem(SPACE_PANEL_STATE);
        // control space panel from localStorage only when it's in closed state
        // if we want to persist "opened" state, we need to fix a problem when we see invitation
        // to cloud before sign-in state is propagated from iframes
        // it can be difficult to detect and differentiate from the case where user uses space-panel
        // to use registry and streamed-nodes
        if (spacePanelStatePersisted === "false") {
            dispatch(setSpacePanelStatusAction({ isActive: false }));
        }
        else {
            dispatch(setSpacePanelStatusAction({ isActive: isSignedIn }));
        }
    }, [dispatch, isSignedIn]);
    const streamedHostsData = getStreamedNodes(chartsMetadata);
    const hasStreamedHosts = streamedHostsData.streamedHosts.length > 0;
    const registry = useSelector(selectRegistry);
    const isUsingGlobalRegistry = useSelector(selectIsUsingGlobalRegistry);
    const machinesArray = ((_a = registry) === null || _a === void 0 ? void 0 : _a.registryMachinesArray) || [];
    const isCloudEnabled = useSelector(selectIsCloudEnabled);
    return (React.createElement(S.PanelContainer, { isActive: panelIsActive, isSignedIn: isSignedIn }, isSignedIn
        ? React.createElement(SpacePanelIframe, { cloudBaseURL: cloudBaseURL, streamedHostsData: streamedHostsData })
        : (React.createElement(React.Fragment, null,
            React.createElement(S.ScrollContainer, null,
                hasStreamedHosts && (React.createElement(S.PanelSection, { leading: true },
                    React.createElement(ReplicatedNodes, { streamedHostsData: streamedHostsData }))),
                (machinesArray.length > 0) && (React.createElement(S.PanelSection, { leading: !hasStreamedHosts },
                    React.createElement(VisitedNodes, { machinesArray: machinesArray })))),
            React.createElement(S.BottomPanelContainer, null,
                isUsingGlobalRegistry && (React.createElement(S.SwitchIdentity, { onClick: () => {
                        window.switchRegistryModalHandler();
                    } }, "Switch Identity")),
                !isOffline && !hasSignInHistory && isCloudEnabled && (React.createElement(S.BottomPanel, null,
                    React.createElement(S.BottomPanelHeader, null, "Discover your monitoring superpowers"),
                    React.createElement(S.BottomPanelText, null, "Do you know that you can manage a lot of nodes with Netdata Cloud?"),
                    React.createElement(S.SignInButton, { href: signInUrl }, "Sign In to Cloud"))),
                isOffline && hasSignInHistory && (React.createElement(S.BottomPanel, null,
                    React.createElement(S.CantConnect, null, "Can't connect to Netdata Cloud"),
                    React.createElement(S.NoNetworkIcon, { viewBox: noNetwork.viewBox },
                        React.createElement("use", { xlinkHref: `#${noNetwork.id}` })),
                    React.createElement(S.OfflineDescription, null, "Maybe you are behind a firewall or you don\u2019t have connection to the internet"))))))));
};
//# sourceMappingURL=space-panel.js.map