import { useEffect, useReducer } from "react";
import { FEAGlobals } from "../../common/Globals";
const initialState = { downloadItems: [] };
/*
Action Types
*/
const UPDATE = "UPDATE";
const REMOVED = "REMOVED";
const INIT = "INIT";
function reducer(state, action) {
    var _a;
    switch (action.type) {
        case INIT:
            // Initialize the state with the downloadItems saved in FEA. Values are only expected when the UI is reopened.
            return {
                downloadItems: [...state.downloadItems, ...(_a = action.payload) === null || _a === void 0 ? void 0 : _a.reverse()],
            };
        case UPDATE: {
            // Adds or updates the downloadItem if it already exists
            const downloadItemExistsInArray = state.downloadItems.find((downloadItem) => downloadItem.id === action.payload.id);
            const downloadItems = downloadItemExistsInArray
                ? state.downloadItems.map((downloadItem) => downloadItem.id === action.payload.id ? action.payload : downloadItem)
                : [action.payload, ...state.downloadItems];
            return { downloadItems };
        }
        case REMOVED: {
            // Removes the downloadItem from the list of downloads
            const downloadItems = state.downloadItems.filter((downloadItem) => downloadItem.id !== action.payload.id);
            return {
                downloadItems,
            };
        }
        default:
            throw new Error();
    }
}
/**
 * A hook to handle state from the download Manager UI. The state is initialized and updated
 * based on information from fea.
 */
export default function useDownloadItems() {
    const [state, dispatch] = useReducer(reducer, initialState);
    /*
        Action Creators
    */
    const removeDownloadItem = (downloadItem) => {
        dispatch({ type: REMOVED, payload: downloadItem });
    };
    const updateDownloadItem = (downloadItem) => {
        dispatch({ type: UPDATE, payload: downloadItem });
    };
    const initDownloadItems = (downloadItems) => {
        dispatch({ type: INIT, payload: downloadItems });
    };
    // Listens for message from fea that a download was initiated/updated
    useEffect(() => {
        FEAGlobals.fin.desktop.System.addEventListener("download-update", updateDownloadItem);
        return () => {
            FEAGlobals.fin.desktop.System.removeEventListener("download-update", updateDownloadItem);
        };
    }, []);
    return {
        downloadItems: state.downloadItems,
        removeDownloadItem,
        initDownloadItems,
    };
}
//# sourceMappingURL=useDownloadItems.js.map