/**
 * Created by jhwang on 14-6-23.
 */
/**
 * 桌面程序中的文件读写
 */
define(function (require, exports) {
    var fs = window.require("fs");
    var IOUtilBase = require('./ioutil').IOUtilBase;
    var Appcontext = require('share/assert/js/appcontext').AppContext;
    var ziputil = window.require('ziputil/AddonZip');
    var mkdirp = require('./mkdirp').instance;
    var process = window.require('child_process');

    function IOUtil() {

    }

    IOUtil.prototype = new IOUtilBase();
    IOUtil.prototype.constructor = IOUtil;
    /**
     *   读文件
     * @param filePath
     * @returns {*}
     */
    IOUtil.prototype.readFile = function (filePath) {
        var def = jQuery.Deferred();
        if (!filePath){
            def.resolve(null);
            throw new Error("error argument");
        }else{
            var newBlankSlideName = filePath.match(/newBlank\d{1,}.sco/);
            var newBlackSlideBackImg = null;
            if (newBlankSlideName) {
                //找一下，该新建页是否设置了背景图
                for (var i = 0; i < Appcontext.newBlankSlides.length; i++) {
                    if (Appcontext.newBlankSlides[i][0] == newBlankSlideName) {
                        newBlackSlideBackImg = Appcontext.newBlankSlides[i][1];
                    }
                }
                if (newBlackSlideBackImg) {
                    def.resolve('{"canvas":{"objects":[],"background":null,"backgroundImage":{"type":"image","originX":"left","originY":"top","left":0,"top":0,"width":840,"height":525,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","src":"' + newBlackSlideBackImg + '","filters":[],"crossOrigin":""}},"rels":[],"animationInfo":[],"presentfmt":"1280:800"}');
                } else {
                    def.resolve('{"canvas":{"objects":[],"background":"white"},"rels":[],"animationInfo":[],"presentfmt":"1280:800"}');
                }
            } else {
                fs.readFile(filePath, function (err, data) {
                    if (err) {
                        def.resolve(null);
                        throw err;
                    }
                    def.resolve(data.toString());
                });
            }
        }

        return def.promise();
    };
    /**
     * 写文件
     * @param filePath
     * @param content
     * @returns {*}
     */
    IOUtil.prototype.writeFile = function (filePath, content) {
        var def = jQuery.Deferred();
        if (!filePath)
            throw new Error("error arguement");
        var ct = content || "";
        fs.writeFile(filePath, ct, function (err) {
            if (err) {
                def.resolve(false)
            } else {
                //console.log(filePath, ' saved!');
                def.resolve(true);
            }
        });
        return def.promise();
    };
    IOUtil.prototype.writeFileSync = function (filePath, content) {
        fs.writeFileSync(filePath, content);
    }

    /**
     * 拷贝文件（同步）
     * @param {!string} content 可选，如果为空则认为是写入空字符串
     * @param {!string} filePath 文件路径
     */
    IOUtil.prototype.copyFile = function (src, des) {
        var defer = jQuery.Deferred();
        var fileReadStream = fs.createReadStream(src);
        var fileWriteStream = fs.createWriteStream(des);
        fileReadStream.pipe(fileWriteStream);
        fileWriteStream.on('error', function () {
            console.log('copy failed');
            defer.resolve(false);
        });
        fileWriteStream.on('close', function () {
            console.log('copy over');
            defer.resolve(true);
        });
        return defer.promise();
    }

    IOUtil.prototype.openFile = function (url) {
        fs.openSync(url)
    }
    /**
     * 拷贝文件（异步，慎用，会卡UI）
     * @param {!string} content 可选，如果为空则认为是写入空字符串
     * @param {!string} filePath 文件路径
     */
    IOUtil.prototype.copyFileSync = function (src, des) {
        fs.writeFileSync(des, fs.readFileSync(src));
    }

    /**
     * 深层次拷贝文件夹，包括子目录和文件（异步）
     * @param src
     * @param des
     * @returns {*}
     */
    IOUtil.prototype.copyDir = function (src, des) {
        var outDef = $.Deferred();
        var _self = this;
        var _dirList=[];
        var _fileList=[];
        var _dirIndex=0;
        _countDirList(src,des);
        console.log(_dirList);
        console.log(_fileList);
        _copyDir();

        function _countDirList(src, des){
            _dirList.push(des);
            var fileList = fs.readdirSync(src);
            for (var i = 0; i < fileList.length; i++) {
                var isDir = fs.lstatSync(src + "/" + fileList[i]).isDirectory();
                if (isDir) {
                    _countDirList(src+ "/" + fileList[i], des+ "/" + fileList[i])
                }else{
                    _fileList.push([src+ "/" + fileList[i],des+ "/" + fileList[i]]);
                }
            }
        }

        function _copyDir(){
            //console.log(_dirList[_dirIndex]);
            _self.mkdir(_dirList[_dirIndex]).done(function(){
                _dirIndex++;
                //console.log(_dirIndex);
                if(_dirIndex < _dirList.length){
                    _copyDir();
                }else{
                    //console.log("文件夹拷贝完毕");
                    _copyFiles();
                    outDef.resolve();
                }
            });
        }

        function _copyFiles(){
            for(var i=0; i<_fileList.length; i++){
                //console.log(_fileList[i][1]);
                _self.copyFileSync(_fileList[i][0],_fileList[i][1]);
            }
        }
        return outDef.promise();
    }

    IOUtil.prototype.readFileSync = function (path) {
        return fs.readFileSync(path).toString();
    }
    IOUtil.prototype.mkdir = function (dirpath) {
        var def = jQuery.Deferred();
        var t = this.exists(dirpath);
        t.done(function (exist) {
            if (!exist) {
                fs.mkdir(dirpath, function (err) {
                    if (err) throw err;
                    def.resolve(true);
                });
            } else {
                def.resolve(true);
            }
        });

        return def.promise();
    };

    /**
     * 创建目录
     * @param dirpath
     * @returns {*}
     */
    IOUtil.prototype.mkdirp = function (dirpath) {
        var def = jQuery.Deferred();
        mkdirp.def(dirpath, function (err) {
            if (err) {
                def.resolve(false)
                throw err;
            }
            //console.log(dirpath, ' saved!');
            def.resolve(true);
        });
        return def.promise();
    };

    /**
     * 写img
     * @param imgData
     * @param name
     * @returns {*}
     */
    IOUtil.prototype.writeIMG = function (name, imgData) {
        var def = jQuery.Deferred();
        var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
        var dataBuffer = new Buffer(base64Data, 'base64');
        fs.writeFile(name, dataBuffer, function (err) {
            if (err) throw err;
            //callback(true)
            def.resolve(true);
        });
        return def.promise();
    }

    /**
     * 删除目录
     * @param dirpath
     * @returns {*}
     */
    IOUtil.prototype.rmdir = function (dirpath) {
        var def = jQuery.Deferred();
        var files = [];
        var fun = arguments.callee;
        if (fs.existsSync(dirpath)) {
            if (fs.statSync(dirpath).isDirectory()) {
                files = fs.readdirSync(dirpath);
                files.forEach(function (file) {
                    var curPath = dirpath + "/" + file;
                    if (fs.statSync(curPath).isDirectory()) { // recurse
                        fun(curPath);
                    } else { // delete file
                        fs.unlinkSync(curPath);
                    }
                });
                fs.rmdirSync(dirpath);
                def.resolve(true);
            }
            else {
                fs.unlinkSync(dirpath);
                def.resolve(true);
            }
        }
        else {
            def.resolve(true);
        }
        return def.promise();
    };

    /**
     * 删除未使用到的文件
     * @param dirpath   目录
     * @param files 在使用的文件名
     */
    IOUtil.prototype.removeCorpseFile = function (dirpath, files) {
        var def = jQuery.Deferred();
        var _nfs = fs.readdirSync(dirpath);
        var _t = 0;
        var _that = this;

        function checkFile() {

            if (_t < _nfs.length) {
                var _is = false;
                for (var m = 0; m < files.length; m++) {
                    if (files[m].toLocaleLowerCase() == _nfs[_t].toLocaleLowerCase()) {
                        _is = true;
                        break;
                    }
                }
                if (_is) {
                    _t++;
                    checkFile();
                }
                else {
                    _that.rmdir(Appcontext.joinPath(dirpath, _nfs[_t])).done(function () {
                        _t++;
                        checkFile();
                    })
                }
            } else {
                def.resolve(true);
            }
        }

        checkFile();
        return def.promise();
    }

    /**
     * 读取目录下的所有文件列表
     * @param _dir
     */
    IOUtil.prototype.readFileList = function (_dir) {
        return fs.readdirSync(_dir);
    }

    IOUtil.prototype.removeFile = function (path) {
        var def = jQuery.Deferred();
        fs.unlink(path, function (_is) {
            def.resolve(_is);
        });
        return def.promise()
    }

    //检查文件
    IOUtil.prototype.exists = function (path) {
        var def = jQuery.Deferred();
        fs.exists(path, function (exists) {
            //if (err) throw err;
            //console.log(dirpath, ' remove!');
            def.resolve(exists);
        });
        return def.promise()
    };
    /**
     * 文件解压缩
     * @param srcPath
     * @param destPath
     * @returns {*}
     */
    IOUtil.prototype.unZip = function (srcPath, destPath) {
        if (!srcPath || !destPath) return;
//        srcPath=Utils.path.trimPosix(srcPath);
//        destPath=Utils.path.trimPosix(destPath);
        var _that = this;
        var defer = $.Deferred();
        _that.exists(destPath).done(function (is) {
            var _f = is ? '-r -y' : '-r';
            /*process.exec('"'+Appcontext.pluginPath()+'7z" x "'+Appcontext.joinPath(srcPath)+'" -o"'+destPath+'" *.* '+_f , function(err, stdout , stderr ) {
             defer.resolve(err ?false : true);
             });*/
            ziputil.unZipFile(Appcontext.joinPath(srcPath), destPath, function (err, code) {
                defer.resolve(code ? false : true);
            });
        })

        return defer.promise();
    }
    //用于PPT
    IOUtil.prototype.unZipPPT = function (srcPath, destPath) {
        if (!srcPath || !destPath) return;
        var defer = $.Deferred();
        /*this.exists(destPath).done(function(is){
         var _f = is?'-r -y':'-r';
         ziputil.unZipFile(srcPath,destPath, function(err, code  ) {
         defer.resolve(code?false:true);
         });
         })*/
        this.exists(destPath).done(function (is) {
            var _f = is ? '-r -y' : '-r';
            process.exec('"' + Appcontext.pluginPath() + '7z" e "' + srcPath + '" -o"' + destPath + '" ppt/media/*.* ' + _f, function (err, stdout, stderr) {
                console.log(err);
                defer.resolve(err ? false : true);
            });
        })
        return defer.promise();
    }
    /**
     * 转换媒体
     * @param srcPath
     * @param destPath
     * @returns {*}
     */
    IOUtil.prototype.ffmpeg = function (srcPath, destPath) {
        if (!srcPath || !destPath) return;
        var defer = $.Deferred();
        var _str = '"' + Appcontext.pluginPath() + 'ffmpeg" -i "' + srcPath + '"  -vcodec libx264  "' + destPath + '"';
        window.ffmid = process.exec(_str + ' -y', function (err, stdout, stderr) {
            defer.resolve(err ? false : true);
        });
        return defer.promise();
    };
    //取视频信息
    IOUtil.prototype.getMediaThemb = function (srcPath, destPath,size) {
        if (!srcPath) return;
        var defer = $.Deferred();
        var _str = '"' + Appcontext.pluginPath() + 'ffmpeg" -i "' + srcPath + '" -y';
        var _size = size || '600x400';
        if (destPath) _str += ' -f image2 -ss 8 -t 0.001 -s '+_size+' "' + destPath + '"'
        window.ffmid = process.exec(_str, function (err, stdout, stderr) {
            defer.resolve(stderr);
        });
        return defer.promise();
    };

    IOUtil.prototype.shellexecute = function (arg) {
        process.exec(arg);
    };

    exports.IOUtil = new IOUtil();
});