'use strict';

// var fstream = require('fstream');
// var tar = require('tar');
// var zlib = require('zlib');
var path = require('path');
var fs = require('fs');


function copy(src,dst){
    let paths = fs.readdirSync(src); //同步读取当前目录
    paths.forEach(function(path){
        var _src=src+'/'+path;
        var _dst=dst+'/'+path;
        fs.stat(_src,function(err,stats){  //stats  该对象 包含文件属性
            if(err)throw err;
            if(stats.isFile()){ //如果是个文件则拷贝 
                let  readable=fs.createReadStream(_src);//创建读取流
                let  writable=fs.createWriteStream(_dst);//创建写入流
                readable.pipe(writable);
            }else if(stats.isDirectory()){ //是目录则 递归 
                checkDirectory(_src,_dst,copy);
            }
        });
    });
}

function checkDirectory(src,dst,callback){
    fs.access(dst, fs.constants.F_OK, (err) => {
        if(err){
            fs.mkdirSync(dst);
            callback(src,dst);
        }else{
            callback(src,dst);
        }
      });
};

function onBeforeBuildFinish (options, callback) {
	/*
    Editor.log('Custom building onBeforeBuildFinish start: ' + options.platform + ' to ' + options.dest); // 你可以在控制台输出点什么

	//game.js
    var gameJsPath = path.join(options.dest, 'game.js');
    var gameData = fs.readFileSync(gameJsPath, 'utf8').split(/\r\n|\n|\r/gm); 
	var insertCode = "require('sdk/ald-game.js');";
	gameData.splice(0, 0, insertCode);
    fs.writeFileSync(gameJsPath, gameData.join('\r\n'));

	Editor.log('Custom building onBeforeBuildFinish end'); 
	*/
    callback();
}

function onBuildFinish (options, callback) {
	Editor.log('Custom building onBuildFinish start'); 
	
	checkDirectory(path.join(options.dest, '../../build-templates/lastCopy/'), options.dest, copy);

	Editor.log('Custom building onBuildFinish end'); 
	callback();
}

/*
'build-start'：构建开始时触发。
'before-change-files'：在构建结束 之前 触发，此时除了计算文件 MD5、生成 settings.js、原生平台的加密脚本以外，大部分构建操作都已执行完毕。我们通常会在这个事件中对已经构建好的文件做进一步处理。
'build-finished'：构建完全结束时触发。
*/
module.exports = {
  load () {
    // execute when package loaded
	Editor.log('load');
	Editor.Builder.on('before-change-files', onBeforeBuildFinish);
	Editor.Builder.on('build-finished', onBuildFinish);
  },

  unload () {
    // execute when package unloaded
	Editor.Builder.removeListener('before-change-files', onBeforeBuildFinish);
	Editor.Builder.removeListener('build-finished', onBuildFinish);
  },
};