import { useEffect } from "react";
import { openQuitConfirmationDialog } from "../components/shared/openQuitConfirmationDialog";
import { FEAGlobals } from "../../common/Globals";
/**
 * Function to bring toolbar to front (since dockable toolbar can be hidden)
 * @param {boolean} focus If true, will also focus the toolbar
 */
const bringToolbarToFront = ({ focus }) => {
    FEAGlobals.finsembleWindow.bringToFront(null, (err) => {
        if (err) {
            FEAGlobals.FSBL.Clients.Logger.system.error("bringToolbarToFront failed, error:", err);
        }
        if (focus) {
            FEAGlobals.finsembleWindow.focus();
        }
    });
};
/**
 * Hides the toolbar
 */
const hideToolbar = () => {
    FEAGlobals.finsembleWindow.blur();
    FEAGlobals.finsembleWindow.hide();
};
/**
 * Shows the toolbar left-aligned to the user's mouse.
 */
const showToolbar = () => {
    FEAGlobals.FSBL.Clients.RouterClient.transmit("DockingService.showAtMousePosition", {
        windowName: FEAGlobals.finsembleWindow.name,
        uuid: FEAGlobals.finsembleWindow.uuid,
    });
    bringToolbarToFront({ focus: true });
};
/**
 * Docks the toolbar to the primary monitor
 */
const dockToolbar = () => {
    FEAGlobals.FSBL.Clients.RouterClient.transmit("DockingService.dockWindow", {
        windowName: FEAGlobals.finsembleWindow.name,
        uuid: FEAGlobals.finsembleWindow.uuid,
    });
};
/**
 * Minimizes all windows.
 */
const minimizeAllWindows = () => {
    FEAGlobals.FSBL.Clients.WorkspaceClient.minimizeAll();
};
/**
 * Brings all windows to front.
 */
const revealAllWindows = async () => {
    await FEAGlobals.FSBL.Clients.WorkspaceClient.bringWindowsToFront();
    bringToolbarToFront({ focus: false });
};
/**
 * Toggles Auto Arrange for all windows on the same monitor as the toolbar
 */
const toggleAutoArrange = async () => {
    /**
     * Bring windows to front before auto arranging them to ensure maximized windows are included in the action
     * This is relies on bringWindowsToFront() restoring maximized and minimized windows
     */
    await FEAGlobals.FSBL.Clients.WorkspaceClient.bringWindowsToFront();
    FEAGlobals.FSBL.Clients.WorkspaceClient.autoArrange({}, () => {
        // This is legacy and we're not sure if it's still required or not.
        // We can try eliminating this once core auto arrange is refactored.
        bringToolbarToFront({ focus: false });
    });
};
/**
 * It's a requirement that the toolbar not be minimized.
 * the minimizable option does not work.
 * Instead, we just listen for this event and restore the window.
 */
const preventMinimize = () => {
    FEAGlobals.finsembleWindow.addEventListener("minimized", () => {
        FEAGlobals.finsembleWindow.restore();
    });
};
/**
 * Required to let the system know that the toolbar is up and ready.
 * Other pieces of the UI key off of this.
 */
const publishSystemCheckpoint = () => {
    FEAGlobals.FSBL.SystemManagerClient.publishCheckpointState("Toolbar", "initialize", "completed");
};
/**
 * Prevents closing of the window.
 */
const onBeforeToolbarUnload = () => {
    openQuitConfirmationDialog();
    // Return of a non-void value (in this `onbeforeunload` handler) is what tells Electron not to close the window.
    // Don't delete this!
    return false;
};
const removeSystemClosePrevention = () => {
    if (window.onbeforeunload === onBeforeToolbarUnload) {
        window.onbeforeunload = null;
    }
};
const launchPreferences = (tabName) => {
    FEAGlobals.FSBL.Clients.RouterClient.transmit("FinsembleUserPreferencesChannel", {
        preferencesTab: tabName,
    });
    FEAGlobals.FSBL.Clients.LauncherClient.showWindow({
        componentType: "UserPreferences",
    }, {
        monitor: "mine",
        left: "center",
        top: "center",
    });
};
/**
 * Prevents the window from going down on alt+f4 or closing from taskbar.
 * Pops up a dialog asking if the user meant to shut down the system.
 */
const preventSystemClose = () => {
    // This function was already called, so no need to run it again.
    if (window.onbeforeunload === onBeforeToolbarUnload)
        return;
    // Bypass system close prevention if for some reason the toolbar has been customized with an alternative onbeforeunload handler
    if (window.onbeforeunload) {
        console.error(`Finsemble toolbar was configured to prevent system closes, however, there is already a function assigned to window.onbeforeunload. In order to prevent the OS from closing your window, we need to overwrite this handler. Users will be able to close your toolbar from the windows taskbar. Please remove your onbeforeunload handler or set the toolbar property 'allowSystemToCloseWindow' to true to get rid of this error message.`);
        return;
    }
    /**
     * From the electron docs:
     * Note: There is a subtle difference between the behaviors of window.onbeforeunload = handler and window.addEventListener('beforeunload', handler). It is recommended to always set the event.returnValue explicitly, instead of only returning a value, as the former works more consistently within Electron.
     *
     * Tried addEventListener, and it wouldn't work.
     */
    window.onbeforeunload = onBeforeToolbarUnload;
    // Detect when the system is being shutdown or restarted to remove the close prevention.
    FEAGlobals.FSBL.Clients.RouterClient.addListener("Application.shutdown", () => {
        removeSystemClosePrevention();
    });
    FEAGlobals.FSBL.Clients.RouterClient.addListener("Application.restart", () => {
        removeSystemClosePrevention();
    });
};
export const useToolbar = () => {
    useEffect(() => {
        preventMinimize();
        publishSystemCheckpoint();
        if (FEAGlobals.FSBL.debug !== true) {
            preventSystemClose();
        }
    }, []);
    return {
        removeSystemClosePrevention,
        preventSystemClose,
        minimizeAllWindows,
        revealAllWindows,
        toggleAutoArrange,
        showToolbar,
        hideToolbar,
        dockToolbar,
        launchPreferences,
    };
};
//# sourceMappingURL=useToolbar.js.map