import { requireNamespace } from '@yeoman/namespace';
export function loadBlueprintsFromConfiguration(config) {
    const configuration = config && config.getAll && typeof config.getAll === 'function' ? config.getAll() || {} : config;
    const blueprints = configuration.blueprints || [];
    const oldBlueprintName = configuration.blueprint;
    if (oldBlueprintName && blueprints.findIndex(e => e.name === oldBlueprintName) === -1) {
        const version = configuration.blueprintVersion || 'latest';
        blueprints.push(parseBlueprintInfo(`${oldBlueprintName}@${version}`));
    }
    return blueprints;
}
export function parseBluePrints(blueprints) {
    if (Array.isArray(blueprints)) {
        return blueprints;
    }
    if (typeof blueprints === 'string') {
        return blueprints
            .split(',')
            .filter(el => el != null && el.length > 0)
            .map(blueprint => parseBlueprintInfo(blueprint));
    }
    return [];
}
export function mergeBlueprints(...blueprintsToMerge) {
    if (!blueprintsToMerge || blueprintsToMerge.length === 0) {
        return [];
    }
    blueprintsToMerge.forEach(blueprints => {
        if (!Array.isArray(blueprints)) {
            throw new Error('Only arrays are supported.');
        }
    });
    return removeBlueprintDuplicates(blueprintsToMerge.flat());
}
export function removeBlueprintDuplicates(blueprints) {
    const uniqueBlueprints = new Map();
    blueprints.forEach(blueprintToAdd => {
        if (uniqueBlueprints.get(blueprintToAdd.name) === undefined) {
            uniqueBlueprints.set(blueprintToAdd.name, blueprintToAdd.version);
        }
    });
    return [...uniqueBlueprints].map(([name, version]) => {
        if (version === undefined)
            return { name };
        return { name, version };
    });
}
export function parseBlueprintInfo(blueprint) {
    let bpName = normalizeBlueprintName(blueprint);
    const idx = bpName.lastIndexOf('@');
    if (idx > 0) {
        const version = bpName.slice(idx + 1);
        bpName = bpName.slice(0, idx);
        return {
            name: bpName,
            version,
        };
    }
    return {
        name: bpName,
    };
}
export function normalizeBlueprintName(blueprint) {
    try {
        const ns = requireNamespace(blueprint);
        if (ns.unscoped.startsWith('generator-begcode-')) {
            return ns.toString();
        }
        return ns.with({ unscoped: `generator-begcode-${ns.unscoped}` }).toString();
    }
    catch (e) { }
    if (blueprint && blueprint.startsWith('@')) {
        return blueprint;
    }
    if (blueprint && !blueprint.startsWith('generator-begcode')) {
        return `generator-begcode-${blueprint}`;
    }
    return blueprint;
}
