var fs = require("fs");
var path = require("path");
var join = require("path").join;

function getFolderAndFiles(jsonPath) {
    let jsonFiles = [];
    function findJsonFile(path) {
        let files = fs.readdirSync(path);
        files.forEach(function (item, index) {
            let fPath = join(path, item);
            let stat = fs.statSync(fPath);
            if (stat.isDirectory() === true) {
                findJsonFile(fPath);
                jsonFiles.push({ file: false, path: fPath });
            }
            if (stat.isFile() === true) {
                jsonFiles.push({ file: true, path: fPath });
            }
        });
    }
    findJsonFile(jsonPath);
    return jsonFiles;
}

/*
* 修改文件夹名称跟文件名称
*/
function modifyFolderAndFileName(dirPath, destReplaceStr) {
    let replaceStr = "XCODE_TEMPLATE_PROJECT"
    var filePath = path.resolve(dirPath);

    let files = getFolderAndFiles(filePath);

    farr = [".buckconfig", ".eslintrc.js", ".flowconfig", ".git", ".gitattributes", ".gitignore",
        ".prettierrc.js", ".watchmanconfig", "node_modules", "ios/Pods", "gradle-wrapper.jar", "debug.keystore", ".jpg",".gif",".png"];
    files = files.filter((o) => {
        let flag = true;
        farr.forEach((element) => {
            if (o.path.indexOf(element) >= 0) {
                flag = false;
            }
        });
        return flag;
    });

    // 替换文件名
    files.forEach((o, i) => {
        if (o.file) {
            let oldPath = path.resolve(o.path);
            let fileData = fs.readFileSync(oldPath).toString();
            fileData = fileData.replace(new RegExp(`${replaceStr}`, 'ig'), destReplaceStr);

            fs.writeFileSync(oldPath, fileData);

            // 解析路径为pathinfo
            let oldPathParse = path.parse(oldPath);
            // 文件名称替换
            let oldPathParseBaseReplace = oldPathParse.base.replace(replaceStr, destReplaceStr);
            // 拼接新文件路径
            let newPath = path.resolve(oldPathParse.dir, oldPathParseBaseReplace)
            // 重命名
            fs.renameSync(oldPath, newPath);
        }
    });

    // 替换文件夹名
    files.forEach((o, i) => {
        if (o.file === false) {
            let oldPath = path.resolve(o.path);
            // 解析路径为pathinfo
            let oldPathParse = path.parse(oldPath);
            // // 根文件夹名称替换
            // let oldPathParseBaseReplace = oldPathParse.base.replace(replaceStr, destReplaceStr);

            // 忽略大小写替换文件夹名 android 是小写
            let oldPathParseBaseReplace = oldPathParse.base.replace(new RegExp(`${replaceStr}`, 'ig'), destReplaceStr)

            // 拼接新文件夹路径
            let newPath = path.resolve(oldPathParse.dir, oldPathParseBaseReplace)
            // 重命名
            fs.renameSync(oldPath, newPath);
        }
    });
}



// function writeFile(p,text){
//     fs.writeFile(p, text,function (err) {
//         if (!err)
//             console.log("写入成功！")
//     })
// }

//递归创建目录 同步方法
function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            // console.log("mkdirsSync = " + dirname);
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

function _copy(src, dist) {
    var paths = fs.readdirSync(src)
    paths.forEach(function(p) {
        var _src = src + '/' +p;
        var _dist = dist + '/' +p;
        var stat = fs.statSync(_src)
        if(stat.isFile()) {// 判断是文件还是目录
            fs.writeFileSync(_dist, fs.readFileSync(_src));
        } else if(stat.isDirectory()) {
            copyDir(_src, _dist)// 当是目录是，递归复制
        }
    })
}

/*
 * 复制目录、子目录，及其中的文件
 * @param src {String} 要复制的目录
 * @param dist {String} 复制到目标目录
 */
function copyDir(src,dist){
    var b = fs.existsSync(dist)
    // console.log("dist = " + dist)
    if(!b){
        // console.log("mk dist = ",dist)
        mkdirsSync(dist);//创建目录
    }
    // console.log("_copy start")
    _copy(src,dist);
}

function copyDirs(src,dist,callback){
    // console.log("createDocs...")
    copyDir(src,dist);
    // console.log("copyDir finish exec callback")
    if(callback){
        callback();
    }
}

module.exports.modifyFolderAndFileName = modifyFolderAndFileName;
module.exports.copyDirs = copyDirs;
