import { Duplex } from 'stream';
import PQueue from 'p-queue';
import { isFilePending } from 'mem-fs-editor/state';
import TemplateFileFs from './template-file-fs.mjs';
export const createMultiStepTransform = () => {
    const twoStepTemplateQueue = new PQueue({ concurrency: 1, autoStart: false });
    const templateFileFs = new TemplateFileFs({});
    const pendingFiles = [];
    const duplex = Duplex.from(async function* (source) {
        for await (const file of source) {
            if (file.contents && templateFileFs.isTemplate(file.path)) {
                const templateFile = templateFileFs.add(file.path, file.contents.toString());
                if (templateFile.rootTemplate) {
                    twoStepTemplateQueue.add(() => {
                        if (pendingFiles.includes(templateFile.basePath)) {
                            return;
                        }
                        file.path = templateFile.basePath;
                        file.contents = Buffer.from(templateFile.render().concat('\n'));
                    });
                }
                else {
                    delete file.state;
                }
            }
            else if (isFilePending(file)) {
                pendingFiles.push(file.path);
            }
            yield file;
        }
        await twoStepTemplateQueue.start().onIdle();
    });
    duplex.templateFileFs = templateFileFs;
    return duplex;
};
