/*!
 * Copyright 2017 - 2023 by Finsemble, Inc.
 * All rights reserved.
 */
/**
 * The Apps Client (formerly known as the Launcher Client) handles spawning
 * apps and app services, and auxiliary functions such as adding or removing
 * them from config dynamically or retrieving details of running instances
 * (active descriptors).
 *
 * The AppsClient API has capabilities to customize your end user's experience,
 * by altering the apps available to them or customizing them at launch. For
 * example, it can apply custom CSS-like positioning and fully display-aware
 * positioning that deals with idiosyncrasies such as monitors with different
 * scaling resolutions.
 *
 * CSS provides higher level abstractions that help lay out an application
 * that consists of constituent parts.
 * Finsemble has borrowed CSS’s positioning paradigm and applied it to the task
 * of laying out windows on the desktop.
 * For example, this CSS-style positioning allows windows to be positioned on the `left`,
 * `right`, `top`, or `bottom` of the end user’s screen. We've
 * also developed new positions, such as `adjacent`, which allows a child
 * window to spawn adjacent to their parent or another application.
 *
 * Application windows can also be positioned and sized by percentage, relative
 * to the monitor or to each other.
 *
 * The Apps Client frequently uses the parameters <code>windowName</code> and <code>componentType</code>. [Learn more about them here](/docs/productivity/componentTypesAndWindowNames).
 * @module AppsClient
 */
import { getMyWindowIdentifier as getMyWindowIdentifierUtil, clone as cloneObject } from "../common/util";
import Logger from "./logger";
import { FinsembleWindow } from "../common/FinsembleWindow";
import { RouterClient } from "./routerClient";
import SystemManagerClient from "../common/systemManagerClient";
import { getAllMonitorsClientSide, getWhichMonitorClientSide, } from "../common/Monitors";
import { registerComponent, unRegisterComponent, getMonitor, getActiveAndPendingWindowNames, getPendingWindows, getComponentsThatCanReceiveDataTypes, hyperFocus, createWindowGroup, addWindowsToGroup, removeWindowsFromGroup, getGroupsForWindow, addToGroups, } from "../deprecated/deprecatedlauncherClient";
import { bringWindowsToFront, minimizeWindows } from "../common/Desktop";
import { isMouseOverDOMElement } from "../common/util";
// A map of related menus that is kept by handleToggle.
const okayToOpenMenu = {};
/**
 * Utility function that converts a WindowLocator into a WindowIdentifier.
 * @param locator The window locator Object to convert
 * @returns WindowIdentifier
 */
const locatorToIdentifier = (locator) => {
    let windowIdentifier = {};
    if ("windowName" in locator) {
        windowIdentifier.windowName = locator.windowName;
    }
    else {
        windowIdentifier.windowName = "";
    }
    if ("componentType" in locator) {
        windowIdentifier.componentType = locator.componentType;
    }
    if ("uuid" in locator) {
        windowIdentifier.uuid = locator.uuid;
    }
    return windowIdentifier;
};
/**
 * @language javascript, dotnet
 * Get a list of registered components from <i>components.json</i>.
 *
 * ```javascript
 * const {err, data} = await FSBL.Clients.AppsClient.getComponentList();
 * if(!err){
 * 	 console.log(data);
 *   // {
 *   //   "Toolbar": { ... },
 *   //   "Tour": { ... },
 *   //   ...
 *   // }
 * }
 * ```
 *
 * @param cb Callback returns an object map of components. Each component object
 * contains the default config for that component.
 */
export const getComponentList = async (cb) => {
    await SystemManagerClient.waitForStartup("windowService");
    const { err, response } = await RouterClient.query("Launcher.componentList", {});
    cb === null || cb === void 0 ? void 0 : cb(err, response.data);
    return { err, data: response.data };
};
/**
 * @language javascript, dotnet
 * Get the component config for a specific component from <i>components.json</i>.
 *
 * ```javascript
 * const {err, data} = await FSBL.Clients.AppsClient.getComponentDefaultConfig("ChartIQ Example App");
 * ```
 *
 * @param componentType The type of the component.
 * @param cb Callback returns the default config (windowDescriptor) for the requested componentType.
 */
export const getComponentDefaultConfig = async (componentType, cb) => {
    // Note, getComponentList() can be a heavy query. Ideally we would find a way to retrieve just our own config.
    const { err, data } = await getComponentList();
    const componentDescriptor = data === null || data === void 0 ? void 0 : data[componentType];
    cb === null || cb === void 0 ? void 0 : cb(err, componentDescriptor);
    return { err, data: componentDescriptor };
};
/**
 * @language javascript, dotnet
 * Get monitorInfo (dimensions and position) for all monitors. Returns an array of monitorInfo objects. See <a href="/docs/reference/typedocs/modules/AppsClient#getMonitorInfo">AppsClient#getMonitorInfo</a> for the format of a monitorInfo object.
 *
 * ```javascript
 * const {err, data} = await FSBL.Clients.AppsClient.getMonitorInfoAll();
 * if(!err){
 *   console.log(`There are ${data.length} monitors.`);
 * }
 * ```
 *
 * @param cb Returns an array of monitorInfo objects.
 */
export const getMonitorInfoAll = async (cb) => {
    Logger.system.debug("AppsClient.getMonitorInfoAll()");
    return getAllMonitorsClientSide(RouterClient, cb);
};
/**
 * @language javascript, dotnet
 * Get monitor information for a given windowIdentifier or for a specific monitor.
 * If neither the identifier nor monitor are provided, returns the monitorInfo for the current window.
 *
 *
 * The information returned contains:
 *
 * **monitorRect** - The full dimensions for the monitor. <br/>
 * **availableRect** - The dimensions for the available space on the monitor (not including the Windows task bar). <br/>
 * **position** - A number that represents the position of the monitor. The primary monitor is zero. <br/>
 * **whichMonitor** - Contains the string "primary" if it is the primary monitor. <br/>
 *
 * The dimensions are supplemented with the following additional members:
 *
 * **width** - The width calculated as right - left. <br/>
 * **height** - The height calculated as bottom - top. <br/>
 *
 * ```javascript
 * // Get the info for the monitor that the calling app is on
 * const {err, data} = await FSBL.Clients.AppsClient.getMonitorInfo();
 * if(!err){
 *   console.log(data);
 * // Example results:
 * // {
 * //	availableRect: {width, height, bottom, left, ...},
 * //   deviceId: "123456",
 * //   deviceScaleFactor: 2,
 * //   displayDeviceActive: true,
 * //   monitor: {dipRect, scaledRect},
 * //   monitorRect: {width, height, bottom, left, right, ...}
 * //   name: "device0",
 * //   position: 0,
 * //   taskbar: {top, left, right, bottom, width, ...}
 * //   whichMonitor: "primary"
 * // }
 * }
 *
 * // Get monitor info for a given window
 * const {err, data} = await FSBL.Clients.AppsClient.getMonitorInfo({
 *   windowIdentifier: {
 *     windowName: "ABC-uuid"
 *   }
 * });
 * if(!err){
 *   console.log(`App ABC-uuid is currently on the monitor with index ${data.position}`);
 * }
 *
 * // Get the dimensions of the first non-primary monitor
 * const {err, data} = await FSBL.Clients.AppsClient.getMonitorInfo({monitor: 1});
 * if(!err){
 *   console.log("Available dimensions for monitor[1]: ", data.monitorRect);
 *   console.log("Available dimensions, minus claimed space, for monitor[1]: ", data.availableRect);
 * }
 * ```
 *
 * @param params
 * @param params.windowIdentifier The windowIdentifier to get the monitorInfo. If undefined, this points to the current window.
 * @param params.monitor If passed then a specific monitor is identified. Valid values include:
 *
 * <b>"mine"</b> - Place the window on the same monitor as the calling window.
 *
 * Integer value from 0-n (0 being the primary monitor).
 *
 * <b>"primary"</b> indicates the user's primary monitor.
 *
 * <b>"all"</b> - Put a copy of the component on each monitor.
 * @param cb Returns a monitorInfo object containing the monitorRect and availableRect.
 *
 * @returns A promise that resolves to a monitorInfo.
 */
export const getMonitorInfo = async (params = {}, cb) => {
    Logger.system.debug("AppsClient.getMonitorInfo()");
    if (params.monitor === "all") {
        Logger.deprecated(`Use of type "all" in AppsClient.getMonitorInfo() is deprecated. Please use AppsClient.getMonitorInfoAll()`);
        return getMonitorInfoAll(cb);
    }
    return getWhichMonitorClientSide(RouterClient, params, cb);
};
/**
 * @language javascript, dotnet
 * Displays a window and relocates/resizes it according to the values contained in parameters. If the specified window is in a group or tabbed, it is unsnapped/ungrouped/untabbed from the other windows.
 * If invoked on a tabbed window or a window in a group, the window is removed from the tab/group.
 *
 * Caution: A window can inherit parameters only once, at the time when it’s spawned. When the component already exists, changing parameters other than positioning arguments (monitor, relativeWindow, top, bottom, left, right, width, height) has no effect.
 *
 * ```javascript
 * FSBL.Clients.AppsClient.showWindow({windowName: "Welcome Component-86-3416-Finsemble", componentType: "Welcome Component"}, {spawnIfNotFound: true}, (err, data)=> {});
 * ```
 * @param windowIdentifier A windowIdentifier. This is an object containing windowName and componentType. If you don't specify windowName, Finsemble tries to find it by componentType.
 * @param params Configuration settings from the <i><a href="/docs/reference/ConfigReference#finsemble-appd---manifest-window">finsemble.appd[].manifest.window</a></i> section of the application manifest may be used as parameters to this function, except for the `options` element.
 * These are the same as <a href="/docs/reference/typedocs/modules/AppsClient#spawn">AppsClient.spawn()</a> with the following exceptions:
 * <ul>
 * 	<li><b>monitor</b> - Same as spawn() except that null or undefined means don't move the window to a different monitor.</li>
 *  <li><b>left</b> - Same as spawn() except that null or undefined means don't move the window from current horizontal location.</li>
 *  <li><b>top</b> - Same as spawn() except that null or undefined means don't move the window from current vertical location.</li>
 *  <li><b>slave</b> - Cannot be set for an existing window. Goes into effect only if the window is spawned. In other words, use this only in conjunction with spawnIfNotFound.</li>
 *  <li><b>spawnIfNotFound</b> - If true, spawns a new window if the requested one cannot be found. Note: only works if the windowIdentifier contains a componentType.</li>
 *  <li><b>autoFocus</b> - Whether or not the window should be in focus when shown.</li>
 * </ul>
 * @param cb Callback to be invoked after the function is completed regardless of whether the call fails or succeeds.
 * Callback contains two arguments in the following order:
 * <ol>
 * 	<li><b>error</b>: an object containing details related to the reason the call failed and where the exception occurred. This object is null if the call has succeeded.</li>
 * 	<li><b>data</b>: an object with the following information:
 * 		<ul>
 * 			<li><b>windowIdentifier</b> - The <a href="/docs/productivity/componentTypesAndWindowNames">WindowIdentifier</a> for the new window.</li>
 * 			<li><b>windowDescriptor</b> - The <a href="/docs/productivity/componentTypesAndWindowNames">WindowDescriptor</a> of the new window.</li>
 * 			<li><b>finWindow</b> - A <code>finWindow</code> object referencing the new window.</li>
 * 		</ul>
 * 	</li>
 * </ol>
 */
export const showWindow = async (windowLocator, params, cb) => {
    if (!params) {
        params = {};
    }
    params = cloneObject(params);
    if (!params.staggerPixels && params.staggerPixels !== 0) {
        params.staggerPixels = 100;
    }
    params.windowIdentifier = locatorToIdentifier(windowLocator);
    const myWindowIdentifier = await getMyWindowIdentifierUtil();
    if (!params.relativeWindow) {
        params.relativeWindow = myWindowIdentifier;
    }
    await SystemManagerClient.waitForStartup("windowService");
    const { err, response } = await RouterClient.query("Launcher.showWindow", params);
    if (err) {
        cb === null || cb === void 0 ? void 0 : cb(err);
        return { err };
    }
    else {
        const name = response.data.windowIdentifier.windowName;
        const { wrap: finWindow } = await FinsembleWindow.getInstance({
            name,
        });
        const data = {
            ...response.data,
            windowIdentifier: {
                ...response.data.windowIdentifier,
                name,
            },
            finWindow,
        };
        cb === null || cb === void 0 ? void 0 : cb(err, data);
        return { err, data: data };
    }
};
/**
 * @language javascript
 * A convenient method for dealing with a common use case of toggling the appearance and disappearance of a child window when a user presses a button of a dropdown menus.
 * Call this method from the click handler for your element. Your child window needs to close itself on blur events.
 * Caution: A window can inherit parameters only once, at the time when it’s spawned. When the component already exists, changing parameters other than positioning arguments (monitor, relativeWindow, top, bottom, left, right, width, height) has no effect.
 * @param element The DOM element, or selector, clicked by the end user.
 * @param windowIdentifier Identifies the child window
 * @param params Parameters to be passed to <a href="/docs/reference/typedocs/modules/AppsClient#showWindow">AppsClient.showWindow()</a> if the child window is allowed to open
 */
export const toggleWindowOnClick = (element, windowLocator, params) => {
    var _a, _b;
    const windowIdentifier = locatorToIdentifier(windowLocator);
    const key = (_b = (_a = windowIdentifier.windowName) !== null && _a !== void 0 ? _a : windowIdentifier.componentType) !== null && _b !== void 0 ? _b : "";
    // If the element was clicked while the menu was open, return right away. The menu window receives a blur event and closes.
    // This method is dependent on the fact that blur events are processed before click events.
    // If this turns out to be a problem,  put this call inside of a setTimeout().
    if (okayToOpenMenu[key] === false) {
        okayToOpenMenu[key] = true;
        return;
    }
    const onDisplayed = (showError, showResponse) => {
        if (!showResponse)
            return;
        const { finWindow } = showResponse;
        const onBlur = () => {
            okayToOpenMenu[key] = true;
            isMouseOverDOMElement(element, (mouseIsOverElement) => {
                okayToOpenMenu[key] = !mouseIsOverElement;
            });
            finWindow.removeEventListener("blurred", onBlur);
        };
        finWindow.addEventListener("blurred", onBlur);
    };
    if (!params.position)
        params.position = "absolute";
    showWindow(windowLocator, params, onDisplayed);
};
const waitForReadySignal = (name) => new Promise((resolve) => {
    // Wait for a definite message that the component is ready (that FSBL has been initialized in the spawned app).
    const subscriberID = RouterClient.subscribe(`Finsemble.${name}.componentReady`, (error, response) => {
        if (error || !response.data) {
            Logger.system.error(`RouterClient.waitForReadySignal() Error subscribing for component ready state ${error}`);
            resolve(error);
            // Ignore the initial "uninitialized" state message delivered by subscribe (the one with an empty string).
        }
        else if (Object.keys(response.data).length) {
            // A second message will arrive with the actual data. Now we know that the client has initialized and signaled its readiness.
            RouterClient.unsubscribe(subscriberID);
            resolve(null);
        }
    });
});
const finalizeSpawnResponse = async (err, response, functionName = "callSpawn") => {
    if (err || !response) {
        const error = err !== null && err !== void 0 ? err : `Internal error: ${functionName}(): No data returned from service for "Launcher.spawn"`;
        return { err: error };
    }
    else {
        const { data: spawnResponseData } = response;
        if (spawnResponseData.stackedWindow) {
            return { err: "Legacy stacked window spawn" };
        }
        let spawnedWindowNames = [];
        let spawnResponse;
        // If we receive an array of spawn response, it means we've spawned a launch group.
        // We select the first spawn response as the result so that a finWindow is available.
        // Additionally, we put all the window names in an array and assign it to a launchGroupWindows
        // property to be placed in the result object so that we have all available window names for the
        // launch group.
        if (Array.isArray(spawnResponseData)) {
            spawnedWindowNames = spawnResponseData.reduce((acc, curr) => {
                acc.push(curr.windowIdentifier.windowName);
                return acc;
            }, []);
            spawnResponse = spawnResponseData[0];
        }
        else {
            spawnResponse = spawnResponseData;
        }
        const name = spawnResponse.windowIdentifier.windowName;
        const { wrap: finWindow } = await FinsembleWindow.getInstance({
            name,
        });
        const result = {
            ...spawnResponse,
            windowIdentifier: {
                ...spawnResponse.windowIdentifier,
                name,
            },
            // Add a wrapped finWindow to the response. You can do this only on the client side.
            finWindow,
        };
        // if we have an array of window names, it means spawn of launchGroup
        // so lets add it to the result.
        if (spawnedWindowNames.length > 0) {
            result.launchGroupWindows = spawnedWindowNames;
        }
        Logger.system.debug(functionName, "Waiting for ready signal", name);
        const waitError = await waitForReadySignal(name);
        Logger.system.debug(functionName, "Got ready signal", name);
        return { err: waitError, result };
    }
};
const callSpawn = async (params) => {
    const { err, response } = await RouterClient.query("Launcher.spawn", params);
    Logger.system.debug("CallSpawn", "Initial launcher callback params", err, response);
    return await finalizeSpawnResponse(err, response, "callSpawn");
};
/**
 * @language javascript, dotnet
 * Asks the Launcher service to spawn a new component. You can also specify any of the following parameters in <i>public/config/components.json</i>, which will
 * then operate as the default for that value.
 *
 * The launcher parameters mimic CSS window positioning.
 * For example, to set a full screen window, use `{left: 0, top: 0, right: 0, bottom: 0}`.
 * This is functionally equivalent to `{left: 0, top: 0, width: "100%", height: "100%"}`.
 *
 * You can also spawn more than one component at a time by using a single action, such as clicking a button on a menu.
 * See https://github.com/ChartIQ/finsemble-seed/tree/recipes/SpawnComponentGroup for an example of spawning a component group.
 *
 * ```javascript
 * FSBL.Clients.AppsClient.spawn("Welcome Component", {left: 0, top: 0, position: "relative"}, (err, data)=> {});
 * ```
 * @param component The application or component to spawn.
 * @param params Configuration settings from the <i><a href="/docs/reference/ConfigReference#finsemble-appd---manifest-window">finsemble.appd[].manifest.window</a></i> section of the application manifest may be used as parameters to this function, except for the `options` element.
 * @param cb Function invoked after the window is created
 */
export const spawn = async (component, params, cb) => {
    if (!params) {
        params = {};
    }
    params = cloneObject(params);
    params.component = component;
    if (!params.options) {
        params.options = {};
    }
    if (!params.options.customData) {
        params.options.customData = {};
    }
    if (!params.staggerPixels && params.staggerPixels !== 0) {
        params.staggerPixels = 50;
    }
    Logger.system.debug(`AppsClient.spawn starting for componentType:${component}`);
    await SystemManagerClient.waitForStartup("windowService");
    const windowIdentifier = await getMyWindowIdentifierUtil();
    params.launchingWindow = windowIdentifier;
    const { err, result: response } = await callSpawn(params);
    Logger.system.debug(`AppsClient.spawn completing for componentType:${component}`, err);
    cb === null || cb === void 0 ? void 0 : cb(err, response);
    return { error: err, response: response };
};
/**
 * @language javascript, dotnet
 * Clone an existing component. Will clone the calling window if no window is specified. Cannot clone freestanding or singleton components.
 *
 * ```javascript
 * FSBL.Clients.AppsClient.clone({windowName:"window-to-clone"}, {left: 0, top: 0}, (err, data) => {});
 * ```
 *
 * @param toClone An optional WindowIdentifier of the window to clone. If you don't provide this parameter,
 * Finsemble tries to clone the calling window.
 * @param spawnParams Optional spawn parameters that override the cloned window params on spawn.
 * @param cb An optional callback that is called when spawn has completed.
 */
export const clone = async (toClone, spawnParams, cb) => {
    if (!spawnParams) {
        spawnParams = {};
    }
    spawnParams = cloneObject(spawnParams);
    Logger.system.debug(`AppsClient.clone starting`, toClone, spawnParams);
    await SystemManagerClient.waitForStartup("windowService");
    spawnParams.launchingWindow = await getMyWindowIdentifierUtil();
    const { err: cloneError, response: cloneResponse } = await RouterClient.query("Launcher.clone", {
        toClone,
        spawnParams,
    });
    const { err, result: response } = await finalizeSpawnResponse(cloneError, cloneResponse, "cloneApp");
    Logger.system.debug(`AppsClient.clone completing for componentType`, toClone, spawnParams, err);
    cb === null || cb === void 0 ? void 0 : cb(err, response);
    return { error: err, response: response };
};
/**
 * @language javascript, dotnet
 * Spawns a set of apps and assembles them into a tab collection. you can specify spawn parameters for the entire collection
 * or for individual apps. However, positioning parameters (e.g. `left` or `top`) are disregarded when set on individual apps.
 *
 * ```javascript
 * await FSBL.Clients.AppsClient.spawnTabCollection({
 *		componentList: [{appID: "Welcome Component", individualParams: { alwaysOnTop : true } }],
 *		globalParams: { left: 100, top: 100}
 *	});
 * ```
 * @param __namedParameters.componentList - The apps to open. Each should be an object that contains the appID (from AppD) and an optional set of SpawnParams.
 * @param __namedParameters.globalParams - Positioning parameters for the collection. If omitted, the collection is spawned in a default location.
 * @returns - Resolves to an object that contains the ID of the tab collection and the list of window names for the spawned apps
 */
export const spawnTabCollection = async ({ componentList, globalParams, }, cb) => {
    Logger.system.debug(`AppsClient.spawn starting for componentType: tabCollection`);
    await SystemManagerClient.waitForStartup("windowService");
    const windowIdentifier = await getMyWindowIdentifierUtil();
    globalParams = globalParams !== null && globalParams !== void 0 ? globalParams : {};
    globalParams.launchingWindow = windowIdentifier;
    const { err, response } = await RouterClient.query("Launcher.spawnTabCollection", {
        componentList,
        globalParams,
    });
    const { id, windows } = response.data;
    let result = {
        id: id,
        windows: [],
    };
    for (const res of windows) {
        const name = res.windowIdentifier.windowName;
        const { wrap: finWindow } = await FinsembleWindow.getInstance({
            name,
        });
        result.windows.push({
            ...res,
            windowIdentifier: {
                ...res.windowIdentifier,
                name,
            },
            // Add a wrapped finWindow to the response (this can only be done client side)
            finWindow,
        });
    }
    Logger.system.debug(`AppsClient.spawn completing for tabCollection`, err);
    cb === null || cb === void 0 ? void 0 : cb(err, result);
    return { err: err, data: result };
};
/**
 * @language javascript, dotnet
 * Returns a windowIdentifier for the current window.
 *
 * ```javascript
 * const myWindowIdentifier = await FSBL.Clients.AppsClient.getMyWindowIdentifier();
 * console.log(myWindowIdentifier);
 * // {
 * //   windowName: "ABC-uuid",
 * //   componentType: "ABC"
 * // }
 * ```
 *
 * @param cb Callback function returns windowIdentifier for this window. (Optional or use the returned Promise)
 * @returns A promise that resolves to a windowIdentifier.
 */
export const getMyWindowIdentifier = async (cb) => {
    const wi = await getMyWindowIdentifierUtil();
    cb === null || cb === void 0 ? void 0 : cb(wi);
    return wi;
};
/**
 * @language javascript, dotnet
 * Gets the windowDescriptor for all open windows.
 *
 * :::note
 * This returns descriptors even if the window is not part of the workspace.
 * :::
 *
 * ```javascript
 * FSBL.Clients.AppsClient.getActiveDescriptors(function (error, response) {
 * 	if (error) {
 *		Logger.system.error("Error getting active descriptors: ",  + JSON.stringify(error));
 *	} else {
 *		const activeDescriptors = response;
 *		//{
 *		//	...
 *		//	Toolbar-1-Finsemble: {...},
 *		//	Welcome-Component-80-6453-Finsemble: {...},
 *		//	...
 *		//}
 * 	}
 * });
 * ```
 * @param cb Callback returns an object containing windowDescriptors keyed by name.
 */
export const getActiveDescriptors = async (cb) => {
    await SystemManagerClient.waitForStartup("windowService");
    const { err, response } = await RouterClient.query("Launcher.getActiveDescriptors", {});
    if (err)
        Logger.system.error(err);
    cb === null || cb === void 0 ? void 0 : cb(err, response.data);
    return { err, data: response.data };
};
/**
 * @private Adds a custom component.
 * @ignore
 */
export const addUserDefinedComponent = async (params, cb) => {
    await SystemManagerClient.waitForStartup("windowService");
    const { err } = await RouterClient.query("Launcher.userDefinedComponentUpdate", {
        type: "add",
        name: params.name,
        url: params.url,
    });
    if (err)
        Logger.system.error(err);
    cb === null || cb === void 0 ? void 0 : cb(err);
    return { err };
};
/**
 * @private Adds a custom component.
 * @ignore
 */
export const removeUserDefinedComponent = async (params, cb) => {
    await SystemManagerClient.waitForStartup("windowService");
    const { err } = await RouterClient.query("Launcher.userDefinedComponentUpdate", {
        type: "remove",
        name: params.name,
        url: params.url,
    });
    if (err)
        Logger.system.error(err);
    cb === null || cb === void 0 ? void 0 : cb(err);
    return { err };
};
/**
 * @language javascript, dotnet
 * Adds to Finsemble new FDC3 App definition(s), in the form of an array of FDC3 2.0 AppD
 * records. After the apps are added, a user can launch them via the Apps
 * Client, `fdc3.open`, `fdc3.raiseIntent` or Toolbar launcher menus.
 *
 * ```javascript
 * const {err, data} = await FSBL.Clients.AppsClient.addApps([anFDC3App]);
 * ```
 *
 * You can update apps by correlating the appIds. Example:
 * ```javascript
 * // Get MyApp
 * const { data: apps } = await FSBL.Clients.AppsClient.getApps(["MyApp"]);
 * const myApp = apps[0];
 *
 * // Update MyApp name to "My App New Name"
 * app.name = `MyApp New Name`;
 *
 * // Update the app in Finsemble
 * await FSBL.Clients.AppsClient.addApps([app]);
 * ```
 *
 * @param apps he array of FDC3 2.0 AppD records (`FDC3AppDefinition`) to add to Finsemble.
 * @param cb The callback to be invoked after the apps are set or on error.
 * @returns A promise that resolves to an array of the added app objects.
 */
export const addApps = async (apps, cb) => {
    if (!Array.isArray(apps)) {
        const err = "The input was not an array. Pass an array of type: FDC3AppDefinition[] (including if only adding a single app)";
        cb === null || cb === void 0 ? void 0 : cb(err);
        return { err };
    }
    const { err, response } = await RouterClient.query("configService.addApps", apps);
    cb === null || cb === void 0 ? void 0 : cb(err, response.data);
    return { err, data: response.data };
};
/**
 * @language javascript, dotnet
 * Removes from Finsemble one or more apps,specified via an array of `appId` values.
 * After an app is removed, it can no longer be launched via the
 * AppsClient, `fdc3.open`, `fdc3.raiseIntent` or launcher menus. Removed
 * applications are automatically removed from launcher menus.
 *
 * Existing instances of the apps are NOT closed automatically when removed,
 * either from the current workspace or saved workspaces. However, saved
 * workspaces containing them are unable to launch them when the workspace
 * is loaded.
 *
 * ```javascript
 * const {err, data} = await FSBL.Clients.AppsClient.removeApps(["fdc3AppId"]);
 * ```
 *
 * @param apps The array of appIds to remove
 * @param cb The callback to be invoked after the apps are removed or on error.
 * @returns A promise that resolves to an array of the removed appId strings.
 */
export const removeApps = async (appIds, cb) => {
    if (!Array.isArray(appIds)) {
        const err = "The input was not an array. Pass an array of string appIds to remove (including if only removing a single app)";
        cb === null || cb === void 0 ? void 0 : cb(err);
        return { err };
    }
    const { err, response } = await RouterClient.query("configService.removeApps", appIds);
    cb === null || cb === void 0 ? void 0 : cb(err, response.data);
    return { err, data: response.data };
};
/**
 * @language javascript, dotnet
 * Retrieves the AppD records for a specified list `appIds` known to Finsemble.
 *
 * @param appIds an array of app IDs to retrieve. If not provided, Finsemble retrieves all apps.
 * @param cb The callback to be invoked after the apps are retrieved or on error.
 * @returns A promise that resolves to an array of app objects.
 */
export const getApps = async (appIds, cb) => {
    if (appIds && !Array.isArray(appIds)) {
        const err = "The input was not an array. Pass an array of string appIds to fetch (including if only retrieving a single app)";
        cb === null || cb === void 0 ? void 0 : cb(err);
        return { err };
    }
    const { err, response } = await RouterClient.query("configService.getApps", appIds);
    cb === null || cb === void 0 ? void 0 : cb(err, response.data);
    return { err, data: response.data };
};
/**
 * @ignore
 */
export const AppsClient = {
    /**
     * For backward compatibility
     * @private
     * @deprecated
     */
    initialize: () => {
        Logger.system.deprecated("It is no longer necessary to call AppsClient.initialized()");
    },
    /**
     * For backward compatibility
     * @private
     * @deprecated
     */
    onReady: (cb) => {
        Logger.system.deprecated("It is no longer necessary to call AppsClient.onReady()");
        cb === null || cb === void 0 ? void 0 : cb();
    },
    addToGroups,
    addUserDefinedComponent,
    addWindowsToGroup,
    bringWindowsToFront,
    clone,
    createWindowGroup,
    getActiveAndPendingWindowNames,
    getActiveDescriptors,
    getComponentDefaultConfig,
    getComponentList,
    getComponentsThatCanReceiveDataTypes,
    getGroupsForWindow,
    getMonitor,
    getMonitorInfo,
    getMonitorInfoAll,
    getMyWindowIdentifier,
    getPendingWindows,
    hyperFocus,
    minimizeWindows,
    registerComponent,
    removeUserDefinedComponent,
    removeWindowsFromGroup,
    showWindow,
    spawn,
    spawnTabCollection,
    toggleWindowOnClick,
    unRegisterComponent,
    addApps,
    removeApps,
    getApps,
};
/**
 * @ignore
 */
export default AppsClient;
//# sourceMappingURL=appsClient.js.map