"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.maxIdNumericSuffix = exports.transformChildNames = exports.cloneFieldWithNewIds = exports.collectNames = exports.stripArrayModePrefix = exports.prefixNameForArrayMode = exports.ARRAY_ITEM_PREFIX = void 0;
const treeWalk_1 = require("./treeWalk.js");
exports.ARRAY_ITEM_PREFIX = 'items[{{index}}].';
const prefixNameForArrayMode = (name) => name.includes('{{index}}') ? name : `${exports.ARRAY_ITEM_PREFIX}${name}`;
exports.prefixNameForArrayMode = prefixNameForArrayMode;
const stripArrayModePrefix = (name) => name.startsWith(exports.ARRAY_ITEM_PREFIX) ? name.slice(exports.ARRAY_ITEM_PREFIX.length) : name;
exports.stripArrayModePrefix = stripArrayModePrefix;
const collectNames = (fields) => {
    const names = new Set();
    (0, treeWalk_1.walkFields)(fields, (field) => {
        if (field.type !== 'section' && field.type !== 'text') {
            names.add(field.name);
        }
    });
    return names;
};
exports.collectNames = collectNames;
const extractBaseName = (name) => {
    const m = name.match(/^(.+?)_copy(?:_\d+)?$/);
    return m ? m[1] : name;
};
const findUniqueCopyName = (originalName, existing) => {
    const stem = extractBaseName(originalName);
    let candidate = `${stem}_copy`;
    let n = 2;
    while (existing.has(candidate)) {
        candidate = `${stem}_copy_${n}`;
        n += 1;
    }
    return candidate;
};
const cloneFieldWithNewIds = (field, generateId, existingNames) => {
    const newId = generateId();
    if (field.type === 'section') {
        return {
            ...field,
            id: newId,
            title: field.title ? `${field.title} (copy)` : 'Section (copy)',
            fields: field.fields.map((child) => (0, exports.cloneFieldWithNewIds)(child, generateId, existingNames)),
        };
    }
    if (field.type === 'text') {
        return { ...field, id: newId };
    }
    const newName = findUniqueCopyName(field.name, existingNames);
    existingNames.add(newName);
    return { ...field, id: newId, name: newName };
};
exports.cloneFieldWithNewIds = cloneFieldWithNewIds;
const transformChildNames = (fields, transform) => fields.map((field) => {
    if (field.type === 'section') {
        return { ...field, fields: (0, exports.transformChildNames)(field.fields, transform) };
    }
    if (field.type === 'text') {
        return field;
    }
    return { ...field, name: transform(field.name) };
});
exports.transformChildNames = transformChildNames;
const maxIdNumericSuffix = (fields) => {
    let max = 0;
    (0, treeWalk_1.walkFields)(fields, (field) => {
        const match = /^fb2_(\d+)$/.exec(field.id);
        if (match) {
            const n = parseInt(match[1] ?? '0', 10);
            if (n > max)
                max = n;
        }
    });
    return max;
};
exports.maxIdNumericSuffix = maxIdNumericSuffix;
//# sourceMappingURL=fieldNames.js.map
