/**
 * Created by baoyinghai on 6/14/17.
 */
var http = require('http');
var extend = require('util')._extend;

var server = http.createServer(function(req, res) {
  console.log(req.url);
  req.url = '/core' + req.url;
  console.log(req.url);
  res.setHeader('Access-Control-Allow-Origin', '*');
  // res.setHeader('Access-Control-Request-Method', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,MX-MainMenuId,MX-ProcessSubMenuId');
  var proxyReq = http.request(extendProxyReqOptions(req), function(proxyRes) {
    proxyRes.pipe(res);
    proxyRes.on('end', () => {
      var endTime = new Date();
      console.log('end');
      // next();
    });
    proxyRes.on('error', (e) => {
      console.log(e);
      // next();
    });
  });

  proxyReq.on('error', e => {
    console.log('redirect to server error!', { err_msg: e });
  });
  req.pipe(proxyReq);
});

function extendProxyReqOptions(req) {
  // var options = req.targetOptions;
  var proxyReqOptions = {};
  proxyReqOptions.host = '192.168.64.71';
  proxyReqOptions.port = 9081;
  proxyReqOptions.path = req.url;
  proxyReqOptions.method = req.method;
  proxyReqOptions.headers = extend({}, req.headers);
  // proxyReqOptions.headers[API_REQ_ID] = options[API_REQ_ID];
  delete proxyReqOptions.headers.host;
  // if (options.headers){
  extend(proxyReqOptions.headers, {
    'MX-TenantIdentifier': 'demo',
    'MX-UserId': '8',
    'MX-UserName': 'xgwen666',
    'MX-DeptId': '1',
    'MX-DeptName': 'xgwen666',
    'request-uuid': '11111111',
  });
  // }
  return proxyReqOptions;
};

console.log("listening on port 3003")
server.listen(3003);
