/*
 * 通用函数
 * */
var _exec = require('child_process').exec;
var _gpio = require('pi-gpio');
var _fs = require('fs');
var g_comm = require('../../comm/comm');

//创建多层文件夹 同步
var mkdirsSync = function(dirpath, mode) {
    if (!fs.existsSync(dirpath)) {
        var pathtmp;
        dirpath.split(path.sep).forEach(function(dirname) {
            if (pathtmp) {
                pathtmp = path.join(pathtmp, dirname);
            }
            else {
                pathtmp = dirname;
            }
            if (!fs.existsSync(pathtmp)) {
                if (!fs.mkdirSync(pathtmp, mode)) {
                    return false;
                }
            }
        });
    }
    return true;
}
exports.mkdirsSync = mkdirsSync;

// echo 17 > /sys/class/gpio/export
// echo 17 > /sys/class/gpio/unexport
// echo out > /sys/class/gpio/gpip17/direction
// echo 1 > /sys/class/gpio/gpip17/value
//设置方向或设置值
var setValueOrDirection = function(pin,data,callback) {
    if (!callback) {
        callback = function () {
        };
    }
    try {
        if (!pin || !data) {
            return;
        }
        pin = pin.toString();
        var cmd = "echo ";
        if (typeof data == 'string') {
            if (data != "in" || data != "out") {
                return;
            }
            cmd += data + " > " + _gpio.p_sysFsPath + "/gpio" + pin + "/direction";
        }
        else if (typeof data == 'number') {
            if (data != 1 || data != 0) {
                return;
            }
            data = data.toString();
            cmd += data + " > " + _gpio.p_sysFsPath + "/gpio" + pin + "/value";
        }
        _exec(cmd, function (err, stdout, stderr) {
            if (err) throw new Error("fail");
            else {
                callback(true);
            }
        });
    }
    catch (e) {
        console.error(e);
        callback(false);
    }
}
exports.setValueOrDirection = setValueOrDirection;

/*
 * 运行Linux命令
 * */
var runCommand = function(cmd,callback){
    _exec(cmd, function (err, stdout, stderr) {
        if(callback && typeof callback == 'function'){
            callback(err,stdout, stderr);
        }
    });
}
exports.runCommand = runCommand;

//读取值
var readValue = function(pin,callback){
    var path = _gpio.p_sysFsPath + "/gpio" + pin + "/value";
    _fs.readFile(path, "utf8", function(err, val) {
        if (err) callback(undefined);
        else {
            if(val) {
                callback(val.toString());
            }
            else{
                callback(undefined);
            }
        }
    });
}
exports.readValue = readValue;

//打开GPIO逻辑脚位
var open = function(pin,callback) {
    if(!pin){
        pin = "0";
    }
    if(!callback){
        callback = function(){};
    }
    var cmd = "echo " + pin.toString() + " > " + _gpio.p_sysFsPath + "/export";
    _exec(cmd, function (err, stdout, stderr) {
        if (err){
            callback(false);
        }
        else{
            callback(true);
        }
    });
}
exports.open = open;

//关闭GPIO逻辑引脚
var close = function(pin,callback){
    if(!pin){
        pin = "0";
    }
    if(!callback){
        callback = function(){};
    }
    var cmd = "echo " + pin.toString() + " > " + _gpio.p_sysFsPath + "/unexport";
    _exec(cmd, function (err, stdout, stderr) {
        if (err){
            callback(false);
        }
        else {
            callback(true);
        }
    });
}
exports.close = close;

//获取已经打开的逻辑引脚脚位
var getLogicPinWithOpened = function(callback){
    if(!callback){
        callback = function(){};
    }
    getAllFiles(_gpio.p_sysFsPath,function(files){
        var f = new Array();
        for(var i in files){
            if(files[i] && files[i] != "export" && files[i] != "unexport" && !g_comm.startWith(files[i],"gpiochip")){
                f.push(files[i].substring(4));
            }
        }
        callback && callback(f);
    });
}
exports.getLogicPinWithOpened = getLogicPinWithOpened;

//关闭所有引脚
var closeAll = function(callback){
    getLogicPinWithOpened(function(pins){
        if(pins && pins.length){
            for(var i in pins){
                close(pins[i]);
            }
        }
        callback && callback();
    });
}
exports.closeAll = closeAll;

var getAllFiles = function (dir, callback) {
    var filesArr = [];
    dir = ///$/.test(dir) ? dir : dir + '/';
        (function dir(dirpath, fn) {
            var files;
            try{files = _fs.readdirSync(dirpath);}catch(e){}
            callback && callback(files);
        })(dir);
    return filesArr;
}

//格式化时间
var dateFormat = function (fmt,date) {
    if (!fmt) {
        fmt = "yyyy-MM-dd hh:mm:ss";
    }
    if (!date) {
        date = new Date();
    }
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
exports.dateFormat = dateFormat;