var fs = require('fs');
var path = require('path');

var base_path = "."

if (process.platform == 'darwin'){	// Mac 路径不同
	base_path = path.join("node_modules", "electron", "dist", "Electron.app", "Contents", "Frameworks", "Electron Helper.app", "Contents", "MacOS")
	base_path = path.join(base_path, "resources")
	if (!fs.existsSync(base_path)){
			console.log(`mkdir ${base_path}...`);
			fs.mkdir(base_path, function(err){
				if(err) throw err;
			})
	}
}else{
	base_path = path.join("build", "Release")
}

console.log(`prepare run environment[${base_path}]...`);
if (!fs.existsSync('node_modules')){
		throw err;
}

if (fs.existsSync('build/Release')){
		console.log('copy liteav.node...');
		fs.copyFile("build/Release/liteav.node", "Release/liteav.node", (err) =>{
			if(err) throw err;
		});
		fs.copyFile("build/Release/imsdk.node", "Release/imsdk.node", (err) =>{
			if(err) throw err;
		});
}


function copyDir(src, dist){
	fs.access(dist, function(err){
		if (err){
			// 目录不存在时创建目录
			fs.mkdirSync(dist);
		}
		fs.readdir(src, function(err, paths){
			if (err) throw err;
			paths.forEach(function(path){
				var _src = src +"/"+path;
				var _dist = dist +"/"+path;
				fs.stat(_src, function(err, stat){
					if (err) throw err;
					if (stat.isFile()){
						fs.copyFile(_src, _dist, (err)=>{
							if (err) throw err;
						})
					}else if (stat.isDirectory()){
						copyDir(_src, _dist);
					}
				})
			})
		})
	})
}
if (process.platform == 'darwin'){	// Mac 下拷贝Framework
	fs.readdir("Frameworks", function(err, files){
		if (err) throw err;
		files.forEach(function(filename){
			if (filename.endsWith(".framework")){
				framwork_path = path.join("node_modules", "electron", "dist", "Electron.app", "Contents", "Frameworks");
				console.log("copy "+filename+" to "+framwork_path+"...");
				copyDir("Frameworks/"+filename, path.join(framwork_path, filename));
			}
		});
	});
}else{
	fs.readdir("Release", function(err, files){
		if (err) throw err;
		files.forEach(function(filename){
			if (filename.endsWith(".dll")){
				console.log('copy '+filename+"...");
				fs.copyFile("Release/"+filename, path.join(base_path, filename), (err) =>{
					if(err) throw err;
				})
			}
		});
	});
}
