var fs = require('fs');
var path = require('path');
var escapeReg = function(str) {
		return str.replace(new RegExp("([.*+?^=!:\x24{}()|[\\]\/\\\\])", "g"), '\\$1');
	};
var run = function (obj) {
	if (!obj[0]) {
		console.log([
				'将文件夹内特定后缀的文件中，24位16进制的id字符串替换为19位10进制的字符串，并保证字符串的首位数字少于5',
				'执行命令 node changeId [目录] 要替换的文件名（支持*号匹配）',
				'注意：目录路径是相对于 changeId.js 的相对路径',
				'例如：',
				'    node changeId *.json',
				'例如：',
				'    node changeId ../_tempData *.json',
				'    node changeId ../_tempData *',
				
			].join('\n'))
		return;
	}
	var fileDirectory=__dirname;
	var fileRegx;
	if(!obj[1]){
		fileRegx=obj[0]
	}else{
		if(obj[0].charAt(1)==':'){
			fileDirectory=obj[0]
		}else{
			fileDirectory=path.join(fileDirectory,obj[0])
		}
		fileRegx=obj[1]
	}
	//console.log(fileRegx);
	fileRegx=fileRegx.replace(/\*/g,'_ANYCHAR_')
	fileRegx=escapeReg(fileRegx);
	fileRegx=fileRegx.replace(/_ANYCHAR_/g,'.*')
	fileRegx='^'+fileRegx+'$'
	fileRegx=new RegExp(fileRegx);
	console.log(['在目录',fileDirectory,'下查找匹配', fileRegx,'的文件'].join(' '));
	if (fs.existsSync(fileDirectory)) {
		var files = fs.readdirSync(fileDirectory);
		var result = [];
		files.forEach(function (filename) {
			if (fileRegx.test(filename)) {
				var data = fs.readFileSync(filename, "utf-8");
				result.push('-- ' + filename);
				var replaced = false;
				data = data.replace(/\b[a-f0-9]{24}\b/gm, function (a, b, c) {
						replaced = true;
						var r = a;
						r = r.replace(/[a-z]/g, function (a) {
								return a.charCodeAt(0) % 9 + 1
							});
						r = '' + Math.max(1,Math.floor(r.substr(1, 1)/2)) + r.substr(2, 6) + r.substr(10, 4) + r.substr(15, 3) + r.substr(19, 5);
						r = r.length > 19 ? r.substr(r.length - 19) : r;
						result.push('   ' + a + ' - ' + r);
						return r
					});
				if (replaced) {
					fs.writeFileSync(filename, data);
				}
			}
		});
		console.log(result.join('\n'));
	} else {
		console.log(fileDirectory + "  Not Found!");
	}
}
//获取除第一个命令以后的参数，转换成数组
run(process.argv.slice(2));
