var fs = require("fs-extra");
var path = require("path");
var AppName = ""
module.exports = {
    /**
     * 递归目录 检查文件名
     * 参考 https://docs.cocos.com/creator/manual/zh/advanced-topics/meta.html
     */
    findDirUuid: function (dir) {
        if(AppName == '') {
            AppName  = this.getRootDirName(dir);
            if(AppName != "") {
                Editor.log("AppName: " + AppName);
            }
        }
        var stat = fs.statSync(dir);
        if (!stat.isDirectory()) {
            return;
        }
        var subpaths = fs.readdirSync(dir),
            subpath;
        for (var i = 0; i < subpaths.length; ++i) {
            if (subpaths[i][0] === ".") {
                continue;
            }
            subpath = path.join(dir, subpaths[i]);
            stat = fs.statSync(subpath);
            if (stat.isDirectory()) {
                this.findDirUuid(subpath);
            } else if (stat.isFile()) {
                var metastr = subpath.substr(subpath.length - 5, 5);
                if (metastr != ".meta") {
                    this.check(AppName, subpaths[i]);
                }
            }
        }
    },

    getRootDirName: function (path) {
        let pArr = path.split("/");
        let assteIndex = -1;
        pArr.find((item, index) => {
            if(item == 'assets') {
                assteIndex = index;
                return true
            } else {
                return false
            }
        })
        if(assteIndex > 0 && assteIndex<(pArr.length-1)) {
            return pArr[assteIndex + 1];
        } else {
            return ""
        }
    },

    check: (appName, filePath) => {
        if(escape(filePath).indexOf("%u")>=0) {
            Editor.log(`检测到[中文或中文符号]命名的文件: ${filePath}`);
        }
        
        if (!/^\S*$/.test(filePath)) {
            Editor.log(`检测到[包含空格]命名的文件: ${filePath}`);
        }
        
        if (/[-]/.test(filePath)) {
            Editor.log(`检测到存在[包含减号（-）]命名的文件: ${filePath}`);
        }

        if(filePath.indexOf(appName) == -1 && (filePath.endsWith(".js") ||  filePath.endsWith(".ts"))) {
            Editor.log(`检测到[不包含包名(${appName})]的文件: ${filePath}`);
        }
    }
};
