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}'";
        this.cmdPostPattern3 = "curl -k -H 'Content-type: application/json'  -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJvcnpaWmhXRXBKNVVFZzRZUU5uUmlyVEJXa1FQbnZ6UyIsImlhdCI6MTU5MjcwOTYzNn0.TWk_F6Tz3fRMqspoG24VSt5RiC4ldFembFYcLcAbowE'  -H 'XAPPKEY: 647a68c9-da01-40d3-9763-1ffa0f64cf3f' -d '{data}' {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;
    }

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

    async execPost3(subData, url) {
        let cmd = this.FetchPostCmd3(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);
// });
