import React, { useEffect, useState } from "react";
import DefaultDropdownButton from "../../../shared/DefaultDropdownButton";
import { FEAGlobals } from "../../../../../common/Globals";
export const DownloadPreferences = (props) => {
    // Download preferences not available under iocd. These can now be set from the download manager.
    if (window.glue42gd) {
        return React.createElement(React.Fragment, null);
    }
    const [initialized, setInitialized] = useState(false);
    const [downloadLocation, setDownloadLocation] = useState("");
    const [previousLocations, setPreviousLocations] = useState([]);
    const [downloadLocationOptions, setDownloadLocationOptions] = useState([]);
    const DOWNLOAD_LOCATION_OPTIONS_LIMIT = 3;
    /**
     * Sets up a dynamic dropdown to track saved locations the user picks.
     * The dropdown can contain the two static options + up to the last three locations
     * selected by the user.
     * @returns
     */
    const createDownloadLocationOptions = () => {
        let downloadOptions = [
            {
                optionLabel: "Ask for each download",
                optionValue: "",
                clickHandler: () => setDownloadLocation(""),
            },
            {
                optionLabel: "New Location",
                optionValue: "new",
                clickHandler: () => {
                    FEAGlobals.finsembleWindow.showNativeOpenDialog({
                        title: "Download Location",
                        buttonLabel: "Choose Location",
                        properties: ["openDirectory"],
                    }, (err, response) => {
                        var _a, _b, _c;
                        if (((_b = (_a = response === null || response === void 0 ? void 0 : response[0]) === null || _a === void 0 ? void 0 : _a.filePaths) === null || _b === void 0 ? void 0 : _b.length) > 0) {
                            const path = (_c = response === null || response === void 0 ? void 0 : response[0]) === null || _c === void 0 ? void 0 : _c.filePaths[0];
                            //  When a new location is selected, update the download location and add it to the dropdown
                            // list and list of previous locations.
                            setDownloadLocation(path);
                            // If the new location selected is already in the dropdown, set it as the download location
                            // but don't add it to the list again
                            if (previousLocations.includes(path))
                                return;
                            if ((previousLocations === null || previousLocations === void 0 ? void 0 : previousLocations.length) >= DOWNLOAD_LOCATION_OPTIONS_LIMIT) {
                                const result = previousLocations.shift();
                                FEAGlobals.FSBL.Clients.Logger.system.debug(`DownloadPreferences: removing oldest option from list: ${result}`);
                            }
                            previousLocations.push(path);
                            setPreviousLocations([...previousLocations]);
                            downloadOptions.push({
                                optionLabel: path,
                                optionValue: path,
                                clickHandler: () => setDownloadLocation(path),
                            });
                        }
                    });
                },
            },
        ];
        Object.values(previousLocations).forEach((location) => {
            downloadOptions.push({
                optionLabel: location,
                optionValue: location,
                clickHandler: () => setDownloadLocation(location),
            });
        });
        return downloadOptions;
    };
    /**
     * Set initial local state from the store
     */
    useEffect(() => {
        props.getPreferences((err, data) => {
            if (data) {
                const configValue = data[props.configKey];
                if (configValue) {
                    setDownloadLocation(configValue.downloadLocation);
                    setPreviousLocations(configValue.previousLocations);
                }
                else {
                    setDownloadLocation("");
                    setPreviousLocations([]);
                }
                // This is a hack to prevent preferences from being saved back from initialization
                setTimeout(() => {
                    setInitialized(true);
                }, 500);
            }
        });
    }, []);
    // Write the store when local state updates. Also keep the dropdown options up to date
    // Only the download location and the list of previous locations is saved in the store.
    // The list of previous locations is used to create the dropdown options.
    useEffect(() => {
        if (initialized) {
            props.setPreferences(props.configKey, { downloadLocation, previousLocations });
            setDownloadLocationOptions(createDownloadLocationOptions());
        }
    }, [downloadLocation, previousLocations, initialized]);
    // Send the download location path down to fea after changes and on startup
    // since it needs to persist between restarts.
    // Note: setDownloadSavePath() is not polyfilled. See ConfigClient setPreferences() for how iocd is informed.
    useEffect(() => {
        var _a, _b, _c;
        if (initialized) {
            (_c = (_b = (_a = FEAGlobals.fin) === null || _a === void 0 ? void 0 : _a.desktop) === null || _b === void 0 ? void 0 : _b.System) === null || _c === void 0 ? void 0 : _c.setDownloadSavePath(downloadLocation);
        }
    }, [downloadLocation, initialized]);
    return (React.createElement("div", null,
        React.createElement("div", { className: "download-header" }, "Downloads"),
        React.createElement("div", { className: "complex-menu-content-row", style: { overflow: "visible" } },
            React.createElement("div", { className: "download-location-row" },
                React.createElement("div", { className: "download-location-label" }, "File download location"),
                React.createElement("div", { className: "download-location-dropdown" },
                    React.createElement(DefaultDropdownButton, { buttonOptions: downloadLocationOptions, classNames: "file-left file-options-left", allowEmpty: false, caretLocation: "right", defaultSelection: downloadLocationOptions.find((element) => element.optionValue === downloadLocation) }))))));
};
export default DownloadPreferences;
//# sourceMappingURL=DownloadPreferences.js.map