"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MigrationHelper = void 0;
const lib_1 = require("tnp-core/lib");
const lib_2 = require("tnp-helpers/lib");
const constants_1 = require("../../../../../constants");
//#endregion
class MigrationHelper extends lib_2.BaseDebounceCompilerForProject {
    //#region constructor
    constructor(project) {
        super(project, {
            folderPath: project.pathFor([
                constants_1.srcMainProject,
                constants_1.libFromSrc,
                constants_1.migrationsFromLib,
            ]),
            taskName: 'MigrationHelper',
            notifyOnFileUnlink: true,
        });
    }
    //#endregion
    //#region migration index autogenerated ts file
    get migrationIndexAutogeneratedTsFileAbsPath() {
        return this.project.pathFor([
            constants_1.srcMainProject,
            constants_1.migrationIndexAutogeneratedTsFileRelativeToSrcPath,
        ]);
    }
    //#endregion
    //#region rebuild
    rebuild(relativePathsWithClasses) {
        //#region @backendFunc
        lib_1.Helpers.taskStarted(`Rebuilding migration index file...`);
        const allClassesByTimestamp = relativePathsWithClasses
            .reduce((acc, c) => acc.concat(c.classes), [])
            .sort((classA, classB) => {
            const timestampA = lib_1.UtilsMigrations.getTimestampFromClassName(classA);
            const timestampB = lib_1.UtilsMigrations.getTimestampFromClassName(classB);
            return timestampA - timestampB; // Ascending order
        });
        const allContexts = allClassesByTimestamp.reduce((alreadyAddedClassesObj, className) => {
            const contextName = lib_1._.first(className.split('_')) || '';
            if (!alreadyAddedClassesObj[contextName]) {
                alreadyAddedClassesObj[contextName] = [];
            }
            alreadyAddedClassesObj[contextName].push(className);
            return alreadyAddedClassesObj;
        }, {});
        const allImports = relativePathsWithClasses
            .filter(c => c.classes.length >= 1)
            .map(c => {
            return (`import { ${c.classes.join(', ')} } from ` +
                `'./${c.relativePath.replace('.ts', '')}';`);
        });
        // console.log('MigrationHelper rebuild for ', allImports);
        // export const MIGRATIONS_CLASSES = [${allClasses.join(',\n')}];
        lib_1.Helpers.writeFile(this.migrationIndexAutogeneratedTsFileAbsPath, `
${constants_1.THIS_IS_GENERATED_INFO_COMMENT}
${allImports.join('\n')}
${constants_1.THIS_IS_GENERATED_INFO_COMMENT}
${lib_1._.keys(allContexts)
            .map(contextName => {
            const classes = allContexts[contextName];
            return (`export const ${constants_1.MIGRATION_CONST_PREFIX}${contextName}` +
                ` = {${classes
                    .map(c => {
                    return `/* ${lib_1.UtilsMigrations.getFormattedTimestampFromClassName(c)} */ ${c}`;
                })
                    .join(',\n ')}};`);
        })
            .join('\n')}
${constants_1.THIS_IS_GENERATED_INFO_COMMENT}
      `);
        lib_2.UtilsTypescript.formatFile(this.migrationIndexAutogeneratedTsFileAbsPath);
        lib_1.Helpers.taskDone(`Rebuilding migration index Done`);
        //#endregion
    }
    //#endregion
    //#region action
    action({ changeOfFiles, asyncEvent, }) {
        //#region @backendFunc
        changeOfFiles = changeOfFiles.filter(c => {
            return (c.fileAbsolutePath.endsWith('.ts') &&
                lib_1.path.basename(c.fileAbsolutePath) !== constants_1.migration_index_autogenerated_ts);
        });
        if (changeOfFiles.length === 0) {
            // console.log('MigrationHelper action skipped');
            return;
        }
        if (!this.project.hasFile([
            constants_1.srcMainProject,
            constants_1.libFromSrc,
            constants_1.migrationsFromLib,
            constants_1.indexTsFromMigrationsFromSrc,
        ])) {
            lib_1.Helpers.writeFile(this.project.pathFor([
                constants_1.srcMainProject,
                constants_1.libFromSrc,
                constants_1.migrationsFromLib,
                constants_1.indexTsFromMigrationsFromSrc,
            ]), `//@ts-nocheck
export * from './${constants_1.migration_index_autogenerated_ts.replace('.ts', '')}';
        `.trim() + '\n');
        }
        // console.log('MigrationHelper action for ', changeOfFiles);
        this.rebuild(this.exitedFilesAbsPathes
            .filter(f => f.endsWith('.ts') && !f.endsWith('._auto-generated_.ts'))
            .map(c => {
            return {
                absPath: c,
                relativePath: this.project
                    .relative(c)
                    .split('/')
                    .slice(3)
                    .join('/'),
                classes: lib_2.UtilsTypescript.extractClassNamesFromFile(c),
            };
        }));
        //#endregion
    }
}
exports.MigrationHelper = MigrationHelper;
//# sourceMappingURL=migrations-helper.js.map