import React, { useCallback, useRef, useEffect } from "react";
import { useEffectOnce } from "react-use";
import { Button, Documentation } from "@netdata/netdata-ui";
import { useDispatch, useSelector } from "../../store/redux-separate-context";
import { selectSnapshot, selectActiveAlarms, selectRegistry, selectIsCloudEnabled, } from "../../domains/global/selectors";
import { getIframeSrc, NETDATA_REGISTRY_SERVER } from "../../utils/utils";
import { isDevelopmentEnv } from "../../utils/env";
import { sendToChildIframe, useListenToPostMessage } from "../../utils/post-message";
import { SvgIcon } from "../svg-icon";
import { showSignInModalAction } from "../../domains/dashboard/actions";
import { LOCAL_STORAGE_NEEDS_SYNC } from "../../domains/dashboard/sagas";
import { alwaysEndWithSlash } from "../../utils/server-detection";
import { CLOUD_BASE_URL_DISABLED } from "../../domains/global/constants";
import { PanelControl } from "./components/panel-control";
import { NodeInfo } from "./components/node-info";
import { AlarmsControl } from "./components/alarms-control";
import { VersionControl } from "./components/version-control";
import { StyledHeader, NavigationSection, UtilitySection, CollapsableSection, WhiteSpaceSection, IconContainer, IframeContainer, SignInButton, OfflineBlock, SignInIframe, } from "./styled";
import offlineBlock from "./offline-block.svg";
const iframeTimeout = isDevelopmentEnv ? 3000 : 750;
const WAITING_FOR_HELLO_TIME = 500;
export const AppHeader = ({ cloudBaseURL, chartsMetadata, isOffline, isSignedIn, enoughWaitingForIframe, hasSignInHistory, onEnoughWaitingForIframe, setIsOffline, signInUrl, }) => {
    var _a, _b;
    const snapshot = useSelector(selectSnapshot);
    const hostname = snapshot ? snapshot.hostname : chartsMetadata.hostname;
    const isCloudEnabled = useSelector(selectIsCloudEnabled);
    const activeAlarms = useSelector(selectActiveAlarms);
    const alarms = activeAlarms ? Object.values(activeAlarms.alarms) : [];
    const criticalAlarmsCount = alarms.filter((alarm) => alarm.status === "CRITICAL").length;
    const warningAlarmsCount = alarms.filter((alarm) => alarm.status === "WARNING").length;
    const registry = useSelector(selectRegistry);
    const name = encodeURIComponent(registry.hostname);
    const origin = encodeURIComponent(alwaysEndWithSlash(window.location.origin + window.location.pathname));
    const iframeUrlSuffix = "&logoutDropdown=true";
    const signInIframeUrl = getIframeSrc(cloudBaseURL, `sign-in?id=${registry.machineGuid}&name=${name}&origin=${origin}${iframeUrlSuffix}`);
    const redirectURI = encodeURIComponent(window.location.href);
    const signInLinkHref = `${signInUrl}&redirect_uri=${redirectURI}`;
    const [helloFromSignIn] = useListenToPostMessage("hello-from-sign-in");
    const helloFromSignInRef = useRef(helloFromSignIn);
    useEffect(() => {
        helloFromSignInRef.current = helloFromSignIn;
    }, [helloFromSignIn]);
    const dropdownHeight = (_a = helloFromSignIn) === null || _a === void 0 ? void 0 : _a.dropdownHeight;
    const dropdownWidth = (_b = helloFromSignIn) === null || _b === void 0 ? void 0 : _b.dropdownWidth;
    const [isLogoutDropdownOpened] = useListenToPostMessage("set-is-logout-dropdown-opened");
    const hasIframeRendered = useRef(false);
    const handleIframeLoad = useCallback(() => {
        // this is called either on success and failure!
        hasIframeRendered.current = true;
        setTimeout(() => {
            if (helloFromSignInRef.current === undefined) {
                // it means it's definitely offline (probably load error)
                setIsOffline(true);
            }
        }, WAITING_FOR_HELLO_TIME);
    }, [setIsOffline]);
    useEffectOnce(() => {
        // alternative way to catch iframe load (error or success) - firefox doesn't work with onLoad
        // attribute when src is unreachable. In Chrome DOMFrameContentLoaded doesn't fire, but it's ok
        // because it's handled by onLoad
        const handler = (event) => {
            var _a;
            if (!((_a = event) === null || _a === void 0 ? void 0 : _a.target)) {
                return;
            }
            const iframeSrc = event.target.src;
            if (iframeSrc === signInIframeUrl) {
                if (hasIframeRendered.current === false) {
                    handleIframeLoad();
                }
            }
        };
        window.addEventListener("DOMFrameContentLoaded", handler);
        return () => {
            window.removeEventListener("DOMFrameContentLoaded", handler);
        };
    });
    // wait a litte bit before we start showing spinners, rendering offline stuff, etc.
    useEffectOnce(() => {
        const timeoutId = setTimeout(() => {
            onEnoughWaitingForIframe();
        }, iframeTimeout);
        return () => {
            clearTimeout(timeoutId);
        };
    });
    const isUsingGlobalRegistry = registry.registryServer === NETDATA_REGISTRY_SERVER;
    const dispatch = useDispatch();
    const handleSignInClick = (event) => {
        if (isUsingGlobalRegistry) {
            // just a link
            return;
        }
        event.preventDefault();
        dispatch(showSignInModalAction({
            signInLinkHref,
        }));
    };
    const signInIframeRef = useRef(null);
    useEffect(() => {
        if (isSignedIn && registry.registryServer && !isUsingGlobalRegistry) {
            const needsSync = localStorage.getItem(LOCAL_STORAGE_NEEDS_SYNC) === "true";
            // that means we were signed in and going back to agent after that
            if (needsSync && signInIframeRef.current) {
                localStorage.removeItem(LOCAL_STORAGE_NEEDS_SYNC);
                const { registryMachinesArray } = registry;
                if (registryMachinesArray && registryMachinesArray.length > 0) {
                    sendToChildIframe(signInIframeRef.current, {
                        type: "synced-private-registry",
                        payload: registryMachinesArray,
                    });
                }
            }
        }
    }, [isSignedIn, isUsingGlobalRegistry, registry]);
    return (React.createElement(StyledHeader, null,
        React.createElement(CollapsableSection, null,
            React.createElement(PanelControl, null),
            React.createElement(NavigationSection, null,
                React.createElement(NodeInfo, { criticalAlarmsCount: criticalAlarmsCount, warningAlarmsCount: warningAlarmsCount, hostname: hostname })),
            React.createElement(WhiteSpaceSection, null)),
        React.createElement(UtilitySection, null,
            !snapshot && (React.createElement(VersionControl, { currentVersion: chartsMetadata.version, releaseChannel: chartsMetadata.release_channel })),
            React.createElement(IconContainer, null,
                React.createElement(Documentation, { app: "agent" }, (toggle) => (React.createElement(Button, { flavour: "borderless", neutral: true, themeType: "dark", className: "btn", icon: "question", onClick: toggle, title: "Need help?" })))),
            React.createElement(IconContainer, null,
                React.createElement(Button, { flavour: "borderless", neutral: true, themeType: "dark", className: "btn", "data-toggle": "modal", "data-target": "#loadSnapshotModal", icon: "download", title: "Import a snapshot" })),
            React.createElement(IconContainer, null,
                React.createElement(Button, { flavour: "borderless", neutral: true, themeType: "dark", className: "btn", "data-toggle": "modal", "data-target": "#saveSnapshotModal", icon: "upload", title: "Export a snapshot" })),
            React.createElement(IconContainer, null,
                React.createElement(Button, { flavour: "borderless", neutral: true, themeType: "dark", className: "btn", "data-toggle": "modal", "data-target": "#printPreflightModal", icon: "print", title: "Print dashboard" })),
            React.createElement(AlarmsControl, { criticalAlarmsCount: criticalAlarmsCount, warningAlarmsCount: warningAlarmsCount }),
            React.createElement(IconContainer, null,
                React.createElement(Button, { flavour: "borderless", neutral: true, themeType: "dark", className: "btn", "data-toggle": "modal", "data-target": "#optionsModal", icon: "gear", title: "Settings" })),
            React.createElement(IframeContainer, null,
                cloudBaseURL !== CLOUD_BASE_URL_DISABLED && isCloudEnabled && (React.createElement(SignInIframe, { ref: signInIframeRef, title: "Sign In", src: signInIframeUrl, width: isLogoutDropdownOpened ? dropdownWidth : "100%", height: isLogoutDropdownOpened ? dropdownHeight : "40px", isShown: isSignedIn, onLoad: handleIframeLoad })),
                enoughWaitingForIframe && hasSignInHistory && isOffline && isCloudEnabled && (React.createElement(OfflineBlock, null,
                    React.createElement(SvgIcon, { icon: offlineBlock, height: 40 }))),
                enoughWaitingForIframe && !hasSignInHistory && !isSignedIn && isCloudEnabled && (React.createElement(SignInButton, { href: isUsingGlobalRegistry ? signInLinkHref : "", isDisabled: isOffline, onClick: handleSignInClick }, "Sign In to Cloud"))))));
};
//# sourceMappingURL=app-header.js.map