//RESTful API  client 代理

var http = require("http");
var uuid = require('uuid/v4');
var URL = require('url');
exports = module.exports = function (logger, settings) {


    function addParams(params) {
        var postData = !params ? '' : JSON.stringify(params || {});
        return postData;
    }


    /* 
    *   var options={
            'host': 'xxx.xxx.xxx.xxx',
            'port': 'xxxxx',
            'path': '/uaa/v1/xxxxx',
            'method': 'POST',
            'params':{},
            'agent': false,
            'headers': {
                "Accept": "application/json",
                "Content-Type": "application/json",
                'User-Agent': 'Request for Express',
                'Authorization':"Bearer " + token
            }
        }
    */

    var client = function (options) {
        return new Promise(function (resolve, reject) {
            var postData = addParams(options.params);
            var httpRequest = http.request(options, function (res) {
                var _data = '';
                res.setEncoding('utf8');
                res.on('data', function (chunk) {
                    _data += chunk;
                });
                res.on('end', function () {
                    resolve(_data, res);
                });
            });
            httpRequest.on('error', function (e) {
                reject(_data, e);
            });
            httpRequest.write(postData);
            httpRequest.end();
        });
    };

    return client;
};


exports['@singleton'] = true;
exports['@require'] = ['igloo/logger', 'igloo/settings'];