import { Package } from "@intelligentgraphics/ig.gfx.multiarticle";
import { createConfigurationServiceOperator } from "./ConfigurationServiceOperator";
import { createPDMOperator } from "./PDMOperator";
export const createSourceRegistry = (serviceManager, articleQuery, scheduler) => {
    const hasSource = (sourceId) => serviceManager.getProductDataManagerForSourceId(sourceId) !==
        undefined ||
        serviceManager.getConfigurationServiceForSourceId(sourceId) !==
            undefined;
    const registerSource = (params) => {
        if (hasSource(params.sourceId)) {
            throw new Error(`Can not overwrite already registered services for sourceId "${params.sourceId}"`);
        }
        if (params.serverType !== undefined) {
            serviceManager.setSourceServerType(params.sourceId, params.serverType);
        }
        if (params.configurationService !== undefined) {
            registerConfigurationService(params.sourceId, params.configurationService);
        }
        else if (params.productDataManager !== undefined) {
            registerProductDataManager(params.sourceId, params.productDataManager);
        }
        else {
            throw new Error(`Refusing to register a new source without an ProductDataManager or ConfigurationService`);
        }
        if (params.catalogManager !== undefined) {
            serviceManager.registerCatalogManager(params.sourceId, params.catalogManager);
        }
        if (params.multiArticles !== undefined) {
            let multiArticles;
            if (params.multiArticles instanceof Package) {
                multiArticles = params.multiArticles;
            }
            else {
                multiArticles = new Package(params.multiArticles);
            }
            serviceManager.registerMultiArticles(params.sourceId, multiArticles);
        }
    };
    const registerProductDataManager = (sourceId, productDataManager) => {
        serviceManager.registerProductDataManager(sourceId, productDataManager);
        serviceManager.registerOperator(sourceId, createPDMOperator(sourceId, productDataManager, articleQuery, scheduler));
    };
    const registerConfigurationService = (sourceId, configurationService) => {
        serviceManager.registerConfigurationService(sourceId, configurationService);
        serviceManager.registerOperator(sourceId, createConfigurationServiceOperator(sourceId, configurationService, articleQuery, scheduler));
    };
    return {
        getBackendForServerType: serviceManager.getBackendForServerType,
        loadBackend: serviceManager.loadBackend,
        registerBackend: serviceManager.registerBackend,
        hasSource,
        registerSource,
        registerConfigurationService,
        registerProductDataManager,
    };
};
