
const https = require('https')
    ,querystring = require('querystring')
    ,urlParse = require('url').parse;

module.exports.httpsRequest = function(url, cb) {
    try {
        https.get(url, (res) => {
            if (res.statusCode !== 200) {
                cb(res.statusCode, null);
                return;
            }
            var body = null;
            res.on('data', (chunk) => {
                body = body ? Buffer.concat([body, chunk], body.length +chunk.length) : Buffer.from(chunk);
            });
            res.on('end', () => {
                try {
                    body = body.toString("utf8");
                    body = JSON.parse(body);
                } catch (e) {}
                cb && cb(res.statusCode, body);
            });
        });
    }
    catch (e) {
        console.error("Error in https request: ", e);
        cb && cb(0, null);
    }
};

module.exports.httpsPost = function(url, postData, cb) {
    var urlObj = urlParse(url);
    var rawData = querystring.stringify(postData);
    try {
        var req = https.request({
                protocol: urlObj.protocol
                ,hostname: urlObj.host
                ,path: urlObj.path
                ,method: "POST"
                ,headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Content-Length": Buffer.byteLength(rawData)
                }
            }, (res) => {
                if (cb) {
                    var body = null;
                    res.on('data', (chunk) => {
                        body = body ? Buffer.concat([body, chunk], body.length +chunk.length) : Buffer.from(chunk);
                    });
                    res.on('end', () => {
                        try {
                            body = JSON.parse(body.toString("utf8"));
                        } catch (e) {}
                        cb(res.statusCode, body);
                    });
                }
        });
        req.write(rawData);
        req.end();
    }
    catch (e) {
        console.error("Error in https request: ", e);
        cb && cb(0, null);
    }
};

