var fs = require('fs')

let folderPath = 'web-mobile';

let pathRequire = require('path');
let pathArr = pathRequire.resolve(__dirname, '..').split("\\"); 
let newfolderPath = pathArr[pathArr.length-1];//'FightingSports'

let fullFilePath = folderPath+'/index.html'

let Package = 
{
	init()
	{
		let self = this;

		this.quoteScriptToIndexHtml(function()
			{
				console.log("1,引入Script到html成功");
				self.copyImg(self,function(picName)
					{
						console.log("2,拷贝图片成功");
						self.changeCssBGPercentageAndPngName(self,picName,function()
						{
							console.log("3,修改Css背景图片百分比成功");
							self.changeFolderName(self,function()
							{
								console.log("4,修改文件夹名成功");
								console.log("\n打包成功!");
							})
						})
					});	
			});
	},
	//引入Script到html
	quoteScriptToIndexHtml(callback)
	{
		let self = this;
		this.readFile(this,fullFilePath,function(str)
		{
			let regExp = /<script src="main(.+?)<\/script>/g;// '<script src="main.870be.js" charset="utf-8"></script>';
			let targetStr = str.match(regExp);
			// console.log(targetStr);

			let addStr = '<script type="text/javascript" src="//js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>';
			let replaceStr = addStr+'\n'+targetStr;
			let newNata = str.replace(targetStr,replaceStr);

			self.writeFile(self,newNata,fullFilePath,callback);
		});
	},
	//拷贝图片
	copyImg(self,callback)
	{
		let reg = /splash.+?png/;// splash.85cfd.png
		
		let pngName = self.matchFileInFolder(folderPath,reg);
		// console.log('png='+pngName);
		if(pngName)
		{
			fs.unlinkSync(folderPath+'/'+pngName);
	
			let picReg = /splash.+?/;// splash.85cfd.png
			let picName = self.matchFileInFolder('./',picReg);
			// console.log('picName='+picName);
			if(picName)
			{
				let aPath = folderPath+'/'+file;
				fs.copyFile(picName,aPath,function(err)
				{
					if(err) {
						console.log('something wrong was happened')
					}
					else 
					{
						let aName = self.getFileName(pngName);
						// console.log('aName='+aName);
						let aTail = self.getFileTail(picName);
						// console.log('aTail='+aTail);
						let newFileName = aName+'.'+aTail;
						// console.log('newFileName='+newFileName);
						// console.log('copy file succeed');

						let oldPath = folderPath+'/'+picName;
						let newPath = folderPath+'/'+newFileName;
						self.rename(oldPath,newPath,function()
						{
							callback(newFileName);
						});
					}
				});
			}	
		}
	},
	// 修改Css背景图片百分比
	changeCssBGPercentageAndPngName(self,picName,callback){
	
		let reg = /style-mobile.+?css/;// style-mobile.6e9cd.css
		let cssName = self.matchFileInFolder(folderPath,reg);

		if(cssName)
		{
			let aPath = folderPath+'/'+file;
			this.readFile(this,aPath,function(str)
			{
				//change percentate
				let targetStr =  'background-size: 45%;';
				let replaceStr =  'background-size: 100%;';
				let newNata = str.replace(targetStr,replaceStr);
				//change png link
				let fileName = self.getFileName(picName);
				// console.log('fileName='+fileName);
				// console.log('picName='+picName);
				let newNata2 = newNata.replace(fileName+'.png',picName);

				// console.log(newNata)
		    	self.writeFile(self,newNata2,aPath,callback);
			});
		}
	},
	//修改文件夹名
	changeFolderName(self,callback)
	{
		let deleteall = function(path) 
		{
			var files = [];
			if(fs.existsSync(path)) 
			{
				files = fs.readdirSync(path);
				files.forEach(function(file, index) 
				{
					var curPath = path + "/" + file;
					if(fs.statSync(curPath).isDirectory()) 
					{ // recurse
						deleteall(curPath);
					} 
					else 
					{ // delete file
						fs.unlinkSync(curPath);
					}
				});
				fs.rmdirSync(path);
			}
			if(!fs.existsSync(newfolderPath))
			{
				self.rename(folderPath,newfolderPath,callback)
			}
		};
		// delete FightingSports
		deleteall(newfolderPath);
	},
	readFile(self,path,callback)
	{
		fs.readFile(path, function (error, data) 
		{
		  if (error) 
		  {
		     // 在这里就可以通过判断 error 来确认是否有错误发生
		    console.log('读取文件失败了')
		  } 
		  else 
		  {
		      // <Buffer 68 65 6c 6c 6f 20 6e 6f 64 65 6a 73 0d 0a>
		  	// 文件中存储的其实都是二进制数据 0 1
		  	// 这里为什么看到的不是 0 和 1 呢？原因是二进制转为 16 进制了
		  	// 但是无论是二进制01还是16进制，人类都不认识
		  	// 所以我们可以通过 toString 方法把其转为我们能认识的字符
		    // console.log(data.toString())
			var str = data.toString();
			callback(str);
		  }
		});
	},
	writeFile(self,newNata,path,callback)
	{
		// fs.wirteFile有三个参数
		// 1,第一个参数是要写入的文件路径
		// 2,第二个参数是要写入得内容
		// 3,第三个参数是可选参数,表示要写入的文件编码格式,一般就不写,默认就行
		// 4,第四个参数是个回调函数  只有一个参数error,来判断是否写入成功
		fs.writeFile(path, newNata, error => 
		{
		 	if (error) return console.log("写入文件失败,原因是" + error.message);
		 	// console.log("写入成功");
			callback();	
		}); 
	},
	rename(oldPath,newPath,callback)
	{
		//同以目录下的文件更名：
		fs.rename(oldPath,newPath, function(err)
		{
			if(err)
			{
				throw err;
			}
			// console.log('rename done!');
			callback();
		});
	},
	matchFileInFolder(path,reg)
	{
		const files = fs.readdirSync(path);

		for (file of files) {

			let result = reg.test(file);
			if(result)
			{
				return file;
			}
		}

		return null;
	},
	getFileName(name)
	{
		let namePartArr = name.split('.');

		return name.replace('.'+namePartArr[namePartArr.length-1],'');
		// if(name.indexOf('.png')!=-1)
		// {
		// 	return name.split('.png')[0];
		// }
		// else if(name.indexOf('.jpg')!=-1)
		// {
		// 	return name.split('.jpg')[0];
		// }
	},
	getFileTail(name)
	{
		let namePartArr = name.split('.');

		return namePartArr[namePartArr.length-1];

		// if(name.indexOf('.png')!=-1)
		// {
		// 	return 'png';
		// }
		// else if(name.indexOf('.jpg')!=-1)
		// {
		// 	return 'jpg';
		// }

		// return '';
	}
}

let package =  Object.create(Package);
package.init();