const fs = require('fs');
const path = require('path');
const util = require('util');
const deleteDir = util.promisify(fs.rmdir);
const makeDir = util.promisify(fs.mkdir);
const sourcePath = './source'; // 源文件夹路径
const tempPath = './temp'; // 临时文件夹路径
const map = { // 替换规则
    '\\.txt$': '_text',
    '\\.js$': '_js',
};

/**
 * 复制指定文件夹下的所有文件到目标文件夹下
 * @param {string} srcDir - 原文件夹路径
 * @param {string} destDir - 目标文件夹路径
 * @param {Object} options - 可选项，包括以下属性:
 *         - {string} prefix: 重命名前缀。
 *         - {string} suffix: 重命名后缀。
 *         - {string} exclude: 要排除的文件夹名称。
 * @return {Promise}
 */
function copyDir(srcDir, destDir, options = {}) {
    const { prefix = '', suffix = '', exclude = '' } = options;
    const excludeDirs = exclude ? exclude.split(',') : [];

    return new Promise((resolve, reject) => {
        // 创建目标文件夹
        fs.mkdir(destDir, { recursive: true }, (err) => {
            if (err) {
                reject(err);
            } else {
                // 读取原文件夹下的文件和子文件夹
                fs.readdir(srcDir, { withFileTypes: true }, (err, files) => {
                    if (err) {
                        reject(err);
                    } else {
                        // 处理每个文件
                        Promise.all(files.map((file) => {
                            const srcPath = path.join(srcDir, file.name);
                            const destPath = path.join(destDir, `${prefix}${file.name}${suffix}`);

                            // 排除特定文件夹
                            if (excludeDirs.includes(file.name)) {
                                return Promise.resolve();
                            }

                            return new Promise((resolve, reject) => {
                                // 复制文件或递归复制子文件夹
                                if (file.isFile()) {
                                    const readStream = fs.createReadStream(srcPath);
                                    readStream.on('error', reject);
                                    const writeStream = fs.createWriteStream(destPath);
                                    writeStream.on('error', reject);
                                    writeStream.on('finish', resolve);
                                    readStream.pipe(writeStream);
                                } else {
                                    copyDir(srcPath, destPath, options).then(resolve, reject);
                                }
                            });
                        })).then(resolve, reject);
                    }
                });
            }
        });
    });
}



// 替换文件中的文本
const replaceText = async (filePath, map) => {
    let content = await util.promisify(fs.readFile)(filePath, {encoding: 'utf8'});
    for (const [regexStr, replacement] of Object.entries(map)) {
        const regex = new RegExp(regexStr, 'g');
        content = content.replace(regex, replacement);
    }
    await util.promisify(fs.writeFile)(filePath, content, {encoding: 'utf8'});
};

// 替换路径下所有的文件
const replaceFiles = async (folderPath, map) => {
    const files = await util.promisify(fs.readdir)(folderPath);
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const filePath = path.join(folderPath, file);
        const stat = await util.promisify(fs.stat)(filePath);
        if (stat.isDirectory()) {
            await replaceFiles(filePath, map);
        } else {
            await replaceText(filePath, map);
        }
    }
};

// 复制 temp 文件到 src
const copyTempToSrc = async (tempPath, srcPath) => {
    await copyFolder(tempPath, srcPath);
};

// 删除目录
const deleteFolder = async (folderPath) => {
    const files = await util.promisify(fs.readdir)(folderPath);
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const filePath = path.join(folderPath, file);
        const stat = await util.promisify(fs.stat)(filePath);
        if (stat.isDirectory()) {
            await deleteFolder(filePath);
        } else {
            await util.promisify(fs.unlink)(filePath);
        }
    }
    await util.promisify(fs.rmdir)(folderPath);
};


async function renameFolder(oldName, newName) {
    try {
        await fs.promises.rename(oldName, newName);
    } catch (error) {
        console.error('Error:', error);
    }
}

// 执行操作
(async () => {
    // 删除并重新创建 temp 目录
    await deleteFolder(tempPath).finally(() => {
        return makeDir(tempPath);
    })
    // 复制 source 下所有文件到 temp
    await copyDir(sourcePath, tempPath);
    // 调整pages 目录
    await renameFolder(tempPath+'/views', tempPath+'/pages')
    // await copyDir(sourcePath+'/views/', tempPath, {
    //     prefix:'pages'
    // });

    // await copyFolder(sourcePath, tempPath+"/", '', ['views'])
    //
    //  await copyFolder(sourcePath+'/views', tempPath, 'pages')


    // await copyFolder(sourcePath, tempPath);
    // // 替换 temp 下所有文件的文本
    // await replaceFiles(tempPath, map);
    // // 复制 temp 文件夹到 src
    // await copyTempToSrc(tempPath, sourcePath);
    // // 删除 temp 目录
    // await deleteFolder(tempPath);
})();
