/**
 * Created by W.J.Chang on 2014/8/21.
 */

var FileSystemUtil = {};

var _fs = window.require('fs');

var splitPathRe =
    /^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/;

var splitPath = function(filename) {
    var result = splitPathRe.exec(filename);
    return [result[1] || '', result[2] || '', result[3] || '', result[4] || ''];
};


FileSystemUtil.contains = function (arr,itm) {
    if(arr.length <= 0) {
        return false;
    }

    for(var i =0; i<arr.length;i++) {
        if(arr[i] == itm) {
            return true;
        }
    }

    return false;
};

/**
 * 获取扩展名
 * @param path
 * @returns {*}
 */
FileSystemUtil.extname = function(path) {
    return splitPath(path)[3];
};

/**
 * 删除目录下文件,不删除目录,不递归目录
 * @param path
 * @param option
 */
FileSystemUtil.deleteFiles = function(path,option) {
    var files = [];
    if (_fs.existsSync(path)) {
        files = _fs.readdirSync(path);
        for(var i = 0; i < files.length;i++) {
            var curPath = path + "/" + files[i];

            if (_fs.statSync(curPath).isDirectory()) {

            } else { // delete file
                var extname = FileSystemUtil.extname(curPath);
                if(FileSystemUtil.contains(option,extname)) {
                    _fs.unlinkSync(curPath);
                }
            }
        }
    }
};