import { generateId } from "@intelligentgraphics/ig.utilities";
export const createSessionWithLoadingReasons = (session, reasonCollection) => {
    const withLoadingReason = (execute, generateReason = generateId) => (...args) => {
        const reason = generateReason(...args);
        reasonCollection.addLoadingReason(reason);
        try {
            const callResult = execute(...args);
            if (typeof callResult === "object" &&
                typeof callResult["then"] === "function") {
                const res = callResult;
                res.finally(() => reasonCollection.removeLoadingReason(reason));
                return callResult;
            }
            reasonCollection.removeLoadingReason(reason);
            return callResult;
        }
        catch (err) {
            reasonCollection.removeLoadingReason(reason);
            throw err;
        }
    };
    return {
        ...session,
        createArticleFromArticleNumber: withLoadingReason(session.createArticleFromArticleNumber, () => `article_creation_${generateId()}`),
        createArticleFromCatalogItem: withLoadingReason(session.createArticleFromCatalogItem, () => `article_creation_${generateId()}`),
        changeArticleProperties: withLoadingReason(session.changeArticleProperties, comId => `article_configuration_${comId}`),
        changeArticleProperty: withLoadingReason(session.changeArticleProperty, comId => `article_configuration_${comId}`),
        changeProperties: withLoadingReason(session.changeProperties, comIds => `article_configuration_${comIds.join("&")}`),
        changeProperty: withLoadingReason(session.changeProperty, comIds => `article_configuration_${comIds.join("&")}`),
        cloneArticle: withLoadingReason(session.cloneArticle, () => `article_creation_${generateId()}`),
        restoreFromIGXB: withLoadingReason(session.restoreFromIGXB, () => `restoring_igxb`),
        restoreFromArticleList: withLoadingReason(session.restoreFromArticleList, () => `restoring_articlelist`),
        restoreFromServices: withLoadingReason(session.restoreFromServices, () => `restoring_from_services`),
        saveAsIGXB: withLoadingReason(session.saveAsIGXB, () => `saving_igxb`),
        saveAsArticleList: withLoadingReason(session.saveAsArticleList, () => `saving_articelist`),
        saveFromServices: withLoadingReason(session.saveFromServices, () => `saving_to_services`),
        withLoadingReason,
    };
};
