const http = require('http');
var https = require('https');
const BufferHelper = require('./BufferHelper.js');

var Service = function () {
  this.serverHost = null;
  this.serverPort = 80;
};

module.exports = Service;

Service.prototype.request = function(service, args, cb) {
  var self = this;
  
  if(!global.curServer) {
    if(cb) cb(args, {code:-1, message:'请提供服务器信息！'});
    return;
  }

  var httpClient = http;
  var options = {
    method: 'POST',
    path: '/Service'
  };
  if(this.serverHost) {
    options.port = this.serverPort;
    options.hostname = this.serverHost;
  } else {
    options.port = curServer.port;
    options.hostname = curServer.address;
    if(curServer.useHttps) {
      options.json = true;
      options.rejectUnauthorized = true;
      httpClient = https;
    }
  }
  var reqHttp = httpClient.request(options, function(resHttp) {
    resHttp.setEncoding('utf8');
    var bufferHelper = new BufferHelper();
    resHttp.on('data', function (chunk) {
      bufferHelper.concat(new Buffer(chunk));
    });
    resHttp.on('end', function() {
      var postData = bufferHelper.toBuffer().toString();
      bufferHelper = null;
      logger.log('收到HTTP响应数据：'+postData);
      var res = null;
      try {
        res = JSON.parse(postData);
      } catch(err) {
        res = {code: 500, message: err.message};
      }
      if(cb) cb(args, res);
    });
  });

  reqHttp.on('error', function(e) {
    logger.log('发送HTTP请求时发生意外错误：' + e.message);
    if(cb) cb(args, {code:-1, message:e.message});
  });
  
  if(!args) args = {};
  args.service = service;
  var str = JSON.stringify(args);
  logger.log('发送HTTP请求数据：'+str);
  reqHttp.setHeader('Content-Type', 'application/x-www-form-urlencoded');
  reqHttp.write(str);
  reqHttp.end();
};