import { IGXE } from "@intelligentgraphics/igd.core";
export const resolveInitialConfiguration = (params, articleQuery, selection) => {
    const headItem = articleQuery.getHeadItem(params.source);
    if (headItem !== undefined) {
        return joinConfigurations(params.initialConfiguration, headItem.comId, articleQuery);
    }
    if (!params.applySceneConfiguration) {
        return params.initialConfiguration;
    }
    const cloneParent = findSimilarArticle(articleQuery, params.articleNumber.baseArticleNumber, params.source, selection, params.articleNumber.attachTo !== undefined
        ? params.articleNumber.attachTo.comId
        : undefined);
    if (cloneParent === undefined) {
        return params.initialConfiguration;
    }
    if (params.initialConfiguration === undefined) {
        return cloneParent.comId;
    }
    const initialConfiguration = typeof params.initialConfiguration === "string"
        ? articleQuery.getArticleConfiguration(params.initialConfiguration)
        : params.initialConfiguration;
    return joinConfigurations(initialConfiguration, cloneParent.configuration, articleQuery);
};
const findSimilarArticle = (articleQuery, articleId, sourceId, selection = [], attachTargetComId) => {
    if (attachTargetComId !== undefined) {
        return articleQuery.getArticleByComId(attachTargetComId);
    }
    const selectionArticles = articleQuery.getArticlesByComIds(selection);
    // first: try to find the same article number in selection
    const sameFromSelection = selectionArticles.find(article => article.source === sourceId && article.articleId === articleId);
    if (sameFromSelection) {
        return sameFromSelection;
    }
    // second: try to find the same series in selection
    const sameSeriesFromSelection = selectionArticles.find(article => article.source === sourceId);
    if (sameSeriesFromSelection) {
        return sameSeriesFromSelection;
    }
    // third: find the same article in planning
    const sameSeriesArticles = articleQuery.getArticlesOfSource(sourceId);
    const sameInScene = sameSeriesArticles.find(article => article.articleId === articleId);
    if (sameInScene) {
        return sameInScene;
    }
    // forth: take the first article of the same series
    if (sameSeriesArticles) {
        return sameSeriesArticles[0];
    }
    return undefined;
};
const joinConfigurations = (initialConfiguration, otherConfiguration, articleQuery) => {
    if (initialConfiguration === undefined) {
        return otherConfiguration;
    }
    const otherConfigurationObject = typeof otherConfiguration === "string"
        ? articleQuery.getArticleConfiguration(otherConfiguration)
        : otherConfiguration;
    const initialConfigurationObject = typeof initialConfiguration === "string"
        ? articleQuery.getArticleConfiguration(initialConfiguration)
        : initialConfiguration;
    return IGXE.mergePropertyValueChanges(otherConfigurationObject, initialConfigurationObject);
};
