import { useEffect } from "react";
import { useSelector, useDispatch } from "../components/FinsembleProvider";
import { ToolbarActions } from "../actions/toolbarActions";
import { FEAGlobals } from "../../common/Globals";
let storageIsInitialized = false;
let DashbarStore;
const setDashbarItem = (itemName, availableDashbarItems, newDashbarItems) => {
    if (availableDashbarItems.hasOwnProperty(itemName)) {
        const newItem = availableDashbarItems[itemName];
        newItem.id = itemName;
        newDashbarItems.push(newItem);
    }
};
const initializeDistributedStore = async () => {
    FEAGlobals.FSBL.Clients.Logger.system.debug("Dashbar: Initialising dashbar store");
    const storeParams = {
        store: "Finsemble-Dashbar-Store",
        global: true,
        persist: true,
    };
    const { err, data: store } = await FEAGlobals.FSBL.Clients.DistributedStoreClient.createStore(storeParams);
    if (err || !store) {
        const error = `Error initializing dashbar: unable to retrieve stored items, falling back to config: ${err}`;
        FEAGlobals.FSBL.Clients.Logger.system.error(error);
        return;
    }
    DashbarStore = store;
};
/**
 * Fetches an initial list of dashbar items from the persistent distributed store,
 * and if that doesn't exist, from spawnData
 */
const initializeDashbarItems = async () => {
    var _a;
    let dashbarItemList;
    if (DashbarStore && Object.keys(DashbarStore.values).length > 0) {
        dashbarItemList = DashbarStore.values.dashbaritems;
    }
    if (!dashbarItemList) {
        const spawnData = FEAGlobals.FSBL.Clients.WindowClient.getSpawnData();
        if (Array.isArray((_a = spawnData === null || spawnData === void 0 ? void 0 : spawnData.dashbar) === null || _a === void 0 ? void 0 : _a.items)) {
            dashbarItemList = spawnData.dashbar.items;
        }
    }
    if (!dashbarItemList)
        dashbarItemList = [];
    const newDashbarItems = [];
    if (dashbarItemList.length > 0) {
        const { data: availableDashbarItems } = await FEAGlobals.FSBL.Clients.ConfigClient.get([
            "finsemble",
            "availableDashbarItems",
        ]);
        dashbarItemList.forEach((itemName) => setDashbarItem(itemName, availableDashbarItems, newDashbarItems));
    }
    if (!DashbarStore.values.dashbaritems) {
        await DashbarStore.set(["dashbaritems"], dashbarItemList);
        return null;
    }
    else {
        return newDashbarItems;
    }
};
export const useDashbar = () => {
    const dispatch = useDispatch();
    const setDashbarItems = async (err, data) => {
        if (!err && data) {
            const { data: availableDashbarItems } = await FEAGlobals.FSBL.Clients.ConfigClient.get([
                "finsemble",
                "availableDashbarItems",
            ]);
            const newDashbarItems = [];
            // Add the widget name as an id to help identify
            // keys -> widgets when reordering items
            data.value.forEach((item) => setDashbarItem(item, availableDashbarItems, newDashbarItems));
            FEAGlobals.FSBL.Clients.Logger.system.debug("Dashbar: Setting Dashbar Items", availableDashbarItems, newDashbarItems);
            dispatch(ToolbarActions.SET_DASHBAR_ITEMS(newDashbarItems));
        }
    };
    /**
     * This effect initializes the dashbar items in the redux store. The store must only be initialized once. We use the module level variable
     * `storageIsInitialized` as a simple flag to prevent initialization from occuring more than once.
     */
    useEffect(() => {
        const init = async () => {
            if (!storageIsInitialized) {
                storageIsInitialized = true;
                await initializeDistributedStore();
                const newDashbarItems = await initializeDashbarItems();
                if (newDashbarItems)
                    dispatch(ToolbarActions.SET_DASHBAR_ITEMS(newDashbarItems));
                DashbarStore.addListener({ field: "dashbaritems" }, setDashbarItems);
            }
        };
        init();
        return function cleanup() {
            DashbarStore.removeListener({ field: "dashbaritems" }, setDashbarItems);
        };
    }, []);
    const { dashbarItems } = useSelector((state) => state.toolbar);
    const reorderDashbarItems = async ({ oldIndex, newIndex }) => {
        const dashbarItemsNewOrder = [...dashbarItems];
        const dashbarItemToMove = dashbarItemsNewOrder[oldIndex];
        dashbarItemsNewOrder.splice(oldIndex, 1);
        dashbarItemsNewOrder.splice(newIndex, 0, dashbarItemToMove);
        const newOrderList = dashbarItemsNewOrder.map((dashbarItem) => dashbarItem.id);
        FEAGlobals.FSBL.Clients.Logger.system.debug("Dashbar: Reorder items", oldIndex, newIndex);
        DashbarStore.set(["dashbaritems"], newOrderList, () => {
            dispatch(ToolbarActions.REORDER_DASHBAR_ITEMS({ oldIndex, newIndex }));
        });
    };
    return {
        dashbarItems,
        reorderDashbarItems,
    };
};
//# sourceMappingURL=useDashbar.js.map