var childproc = require('child_process');
const util = require('util');
const exec = util.promisify(require('child_process').exec);

class ExecClient {
    constructor() {
        this.cmdPostPattern = "curl -k -H 'Content-type: application/json'  -d '{data}' {url}";
        this.cmdGetPattern = "curl -G -X GET '{url}'";
    }

    async exec(cmd) {
        //await后面表达式返回的promise对象，是then的语法糖，await返回then函数的返回值
        //异常需要try/catch自己捕获或外部catch捕获
        const {stdout, stderr} = await exec(cmd);
        return {stdout, stderr};
    }


    async exec2(cmd) {
        return exec(cmd, {encoding: "base64"});
    }

    FetchPostCmd(subData, url) {
        var data = JSON.stringify(subData);
        var cmd = this.cmdPostPattern.replace(/\{data\}/g,
            data).replace(/\{url\}/g, url);
        console.log(cmd);
        return cmd;
    }

    async execPost(subData, url) {
        let cmd = this.FetchPostCmd(subData, url);
        var result = await this.exec(cmd);
        return result;
    }

    async execPost2(subData, url) {
        let cmd = this.FetchPostCmd(subData, url);
        var result = await this.exec2(cmd);
        return result;
    }

    FetchGetCmd(subData, url) {
        var cmd = this.cmdGetPattern.replace(
            /\{data\}/g, subData).replace(/\{url\}/g, url);
        console.log(cmd);
        return cmd;
    }

    async execGet(subData, url) {
        let cmd = this.FetchGetCmd(subData, url);
        console.log(cmd);
        var result = await this.exec(cmd);
        return result;
    }
    async execGet2(subData, url) {
        let cmd = this.FetchGetCmd(subData, url);
        console.log(cmd);
        var result = await this.exec2(cmd);
        return result;
    }

    async execGetTimeOut(subData, url, timeOut = 5000) {
        //timeOut，单位是毫秒
        let cmd = this.FetchGetCmd(subData, url);
        var options = {
            timeout: timeOut,
        };
        const {stdout, stderr} = await exec(cmd, options);
        return {stdout, stderr};
    }
}

module.exports = ExecClient;
// var x=new RestClient();
// x.execGet("","http://www.163.com").then(function(r){
//   console.log(r.stdout);
//   console.log(r.stderr);
// });
