import { Limiter } from "@intelligentgraphics/ig.utilities";
import { createArticleManager as createBaseArticleManager } from "../ArticleManager";
export const createArticleManager = (serviceManager, articleState, articleQuery, operationResultHandler, applicationState) => {
    const baseArticleManager = createBaseArticleManager(serviceManager, articleState, articleQuery, operationResultHandler, applicationState);
    const articleCreationLimiter = new Limiter(1);
    const createArticleFromCatalogItem = async ({ catalogItem, source: sourceId, ...passThrough }) => {
        const backend = await serviceManager.getSourceBackend(sourceId);
        if (backend === undefined) {
            throw new Error(`No backend has been registered for "${sourceId}", no article number can be created.`);
        }
        const articleNumber = backend.createArticleNumber(catalogItem);
        return enqueueCreateArticleFromArticleNumber({
            ...passThrough,
            source: sourceId,
            articleNumber,
        });
    };
    const enqueueCreateArticleFromArticleNumber = (params) => {
        articleCreationLimiter.clearQueue();
        return articleCreationLimiter.queue(() => createArticleFromArticleNumber(params));
    };
    const createArticleFromArticleNumber = async (params) => {
        const results = [];
        const operator = serviceManager.getOperatorForSourceId(params.source);
        const currentMainArticle = articleQuery.getMainArticle();
        if (currentMainArticle !== undefined) {
            results.push(...(await operator.deleteArticle(currentMainArticle.comId)));
        }
        results.push(...(await operator.addArticle(params)));
        await operationResultHandler.processOperationResults(results);
        return articleQuery.getMainArticleComId();
    };
    const changeMainArticleProperties = (changes) => baseArticleManager.changeArticleProperties(articleQuery.getMainArticleComId(), changes);
    const changeMainArticleProperty = (propertyKey, newValue) => baseArticleManager.changeArticleProperty(articleQuery.getMainArticleComId(), propertyKey, newValue);
    const deleteMainArticle = () => {
        const mainComId = articleQuery.getMainArticleComId();
        if (mainComId === undefined) {
            return Promise.resolve();
        }
        return baseArticleManager.deleteArticle(mainComId);
    };
    return {
        ...baseArticleManager,
        createArticleFromArticleNumber: enqueueCreateArticleFromArticleNumber,
        createArticleFromCatalogItem,
        changeMainArticleProperties,
        changeMainArticleProperty,
        deleteMainArticle,
    };
};
