import React, { useState, useEffect } from "react";
import "../../../../assets/css/userPreferences.css";
import DashbarEditorItem from "./DashbarEditorItem";
import { FEAGlobals } from "../../../../../common/Globals";
const dashbarConfigPath = "finsemble.availableDashbarItems";
const dashbarStorePath = "Finsemble-Dashbar-Store";
const DashbarEditor = (props) => {
    var _a;
    const [dashbarStore, setDashbarStore] = useState(null);
    const [availableItems, setAvailableItems] = useState((_a = props.availableItems) !== null && _a !== void 0 ? _a : []);
    const updateDashbarItems = async (err, data) => {
        try {
            const { data: availableDashbarItems } = await FEAGlobals.FSBL.Clients.ConfigClient.get([
                "finsemble",
                "availableDashbarItems",
            ]);
            const hasEnabledItems = data.value && Array.isArray(data.value) && data.value.length > 0;
            const newDashbarItems = [];
            availableDashbarItems &&
                Object.keys(availableDashbarItems).map((dashbarItemName) => {
                    const newItem = availableDashbarItems[dashbarItemName];
                    if (hasEnabledItems && data.value.includes(dashbarItemName)) {
                        newItem.enabled = true;
                    }
                    else {
                        newItem.enabled = false;
                    }
                    newItem.id = dashbarItemName;
                    newDashbarItems.push(newItem);
                });
            setAvailableItems(newDashbarItems);
        }
        catch (errorUpdatingDashbarItems) {
            FEAGlobals.FSBL.Clients.Logger.system.error("Error updating dashbar items", errorUpdatingDashbarItems);
        }
    };
    const removeItem = async (itemId) => {
        var _a;
        const dashbarItemsResult = await (dashbarStore === null || dashbarStore === void 0 ? void 0 : dashbarStore.get(["dashbaritems"]));
        let dashbaritems = (_a = dashbarItemsResult === null || dashbarItemsResult === void 0 ? void 0 : dashbarItemsResult.data) !== null && _a !== void 0 ? _a : null;
        if (!Array.isArray(dashbaritems)) {
            return;
        }
        const indexToRemove = dashbaritems.findIndex((name) => name === itemId);
        dashbaritems.splice(indexToRemove, 1);
        await (dashbarStore === null || dashbarStore === void 0 ? void 0 : dashbarStore.set(["dashbaritems"], dashbaritems));
    };
    const addItem = async (itemId) => {
        var _a;
        // Update the store with new item, dashbar will parse these values and apply them
        const dashbarItemsResult = await (dashbarStore === null || dashbarStore === void 0 ? void 0 : dashbarStore.get(["dashbaritems"]));
        let dashbaritems = (_a = dashbarItemsResult === null || dashbarItemsResult === void 0 ? void 0 : dashbarItemsResult.data) !== null && _a !== void 0 ? _a : [];
        dashbaritems.push(itemId);
        dashbarStore === null || dashbarStore === void 0 ? void 0 : dashbarStore.set(["dashbaritems"], dashbaritems);
    };
    useEffect(() => {
        (async () => {
            try {
                const { data: availableDashbarItems } = await FEAGlobals.FSBL.Clients.ConfigClient.get([
                    "finsemble",
                    "availableDashbarItems",
                ]);
                FEAGlobals.FSBL.Clients.DistributedStoreClient.getStore({
                    store: dashbarStorePath,
                    global: true,
                }, (error, store) => {
                    if (!store) {
                        return;
                    }
                    const DashbarStore = store;
                    const { dashbaritems } = DashbarStore.values;
                    DashbarStore.addListener({
                        field: "dashbaritems",
                    }, updateDashbarItems);
                    const newDashbarItems = [];
                    const hasEnabledItems = dashbaritems && Array.isArray(dashbaritems) && dashbaritems.length > 0;
                    availableDashbarItems &&
                        Object.keys(availableDashbarItems).map((dashbarItemName) => {
                            const newItem = availableDashbarItems[dashbarItemName];
                            if (hasEnabledItems && dashbaritems.includes(dashbarItemName)) {
                                newItem.enabled = true;
                            }
                            else {
                                newItem.enabled = false;
                            }
                            newItem.id = dashbarItemName;
                            newDashbarItems.push(newItem);
                        });
                    setDashbarStore(DashbarStore);
                    setAvailableItems(newDashbarItems);
                });
            }
            catch (errorInitializingDashbarItems) {
                FEAGlobals.FSBL.Clients.Logger.system.error("Error initializing dashbar preferences", errorInitializingDashbarItems);
            }
        })();
        return () => {
            try {
                dashbarStore === null || dashbarStore === void 0 ? void 0 : dashbarStore.removeListener({ field: "dashbaritems" }, updateDashbarItems);
            }
            catch (error) {
                FEAGlobals.FSBL.Clients.Logger.system.error("Error unmounting component", error);
            }
        };
    }, []);
    if (availableItems.length > 0) {
        return (React.createElement("div", { className: `dashbar-preferences ${props.className || ""}`, style: { paddingLeft: 20, paddingTop: 3 } },
            React.createElement("table", { className: "dashbar-items-table" },
                React.createElement("colgroup", null,
                    React.createElement("col", { className: "db-col-1" }),
                    React.createElement("col", { className: "db-col-2" }),
                    React.createElement("col", { className: "db-col-3" }),
                    React.createElement("col", { className: "db-col-4" })),
                React.createElement("thead", null,
                    React.createElement("tr", { className: "items-header" },
                        React.createElement("th", null),
                        React.createElement("th", null, "Title:"),
                        React.createElement("th", null, "Url:"),
                        React.createElement("th", null, "Width:"))),
                React.createElement("tbody", null, availableItems.map((item, index) => {
                    const buttonAction = item.enabled ? () => removeItem(item.id) : () => addItem(item.id);
                    return (React.createElement(DashbarEditorItem, { key: index, buttonAction: buttonAction, index: index, id: item.id, title: item.title, enabled: item.enabled, url: item.url, width: item.width }));
                })))));
    }
    else {
        return (React.createElement("div", { id: "no-dashbar-items", style: { paddingLeft: 20 } }, `You don't seem to have any dashbar items enabled or defined. Define some in ${dashbarConfigPath}`));
    }
};
export default DashbarEditor;
//# sourceMappingURL=DashbarEditor.js.map