var agent = require("agentkeepalive");
var kAgent = new agent({
  maxSockets: 100,
  keepAlive: true,
  maxFreeSockets: 10,
  keepAliveMsecs: 1000,
  timeout: 60000,
  keepAliveTimeout: 30000
});

// Prevent stopping from failed proxy requests
process.on('uncaughtException', err => {
  console.error('[Proxy]', err)
})

var remote = "https://dev.chemzoo.com:3333";
// var remote = "https://localhost:4443";
var filePreview = "http://localhost:8012/onlinePreview";
var websocketLink = "wss://dev.chemzoo.com/ws";

var onProxyAPIRes = function(proxyRes, req, res) {
  // redirection location rewrite
  let oldLocation = proxyRes.headers["location"];
  if (oldLocation && oldLocation.indexOf('post_login') > 0) {
    let newLocation = "http://localhost:4200/api/post_login";
    proxyRes.headers["location"] = newLocation;
  }
};

function onProxyAPIReq(proxyReq, req, res) {
  // add custom header to request
  let referer = proxyReq.getHeader("Referer");
  if(referer) {
    let newLocation = referer.replace("http://localhost:4200", remote);
    proxyReq.setHeader("Referer", newLocation);
  }
}

function onProxyPreviewReq(proxyReq, req, res) {
  // add custom header to request
  let referer = proxyReq.getHeader("Referer");
  if(referer) {
    let newLocation = referer.replace("http://localhost:4200", filePreview);
    proxyReq.setHeader("Referer", newLocation);
  }
}

const CONFIG = [
  {
    context: ["/api"],
    target: remote,
    secure: false,
    logLevel: "debug",
    onProxyRes: onProxyAPIRes,
    onProxyReq: onProxyAPIReq,
    pathRewrite: {
      "^/api": ""
    },
    changeOrigin: true
  },
  {
    context: ["/preview"],
    target: filePreview,
    secure: false,
    logLevel: "debug",
    onProxyReq: onProxyPreviewReq,
    pathRewrite: {
      "^/preview": ""
    },
    changeOrigin: true
  },
  {
    context: ["/ws"],
    target: websocketLink,
    secure: false,
    pathRewrite: {
      "^/ws": ""
    },
    "ws": true,
    changeOrigin: true
  },
  {
    context: ["/p"],
    target: 'http://localhost:4200/#/p',
    secure: false,
    logLevel: "debug",
    pathRewrite: {
      "^/p": ""
    },
    changeOrigin: true
  }
];

module.exports = CONFIG;
