var httpProxy = require('http-proxy');
var DispatchTable = require('../DispatchTable');
var url = require('url');

function splitFirst(str, delim) {
	var index = str.indexOf(delim);
	if(index == -1)
		return [str];
	return [str.substr(0,index), str.substr(index)];

}

function parseEntry(entry) {
	if(typeof entry == 'number')
		entry = entry.toString();
	if(typeof entry == 'string') {
		if(entry.match(/^\d+(?:|\/.*)$/)) {
			entry = '127.0.0.1:' + entry;
		}
		if(!entry.match('https?\/\/')) {
			entry = 'http://' + entry;
		}
	}
	entry = url.parse(entry, true, true)
	entry.ws = true;
	return entry;
}

var proxy = httpProxy.createProxyServer({agent: null});
var regexpHelper = require('../regexpHelper');

var proxyFailErrorHandler;

proxy.on('error', function(err, req, res) {
	if(proxyFailErrorHandler) {
		return proxyFailErrorHandler(err, req, res);
	}
	// forward to next route and save error for potential handler
	req.err = err;
	req.next();
});

module.exports = {
	priority: 8,
	middleware: function(config) {
		if(!config.router) return;

    if(config.errorHtmlFile) {
      var content = fs.readFileSync(config.errorHtmlFile).toString('utf8');

      content = content.replace(/src="(.+?)"/g, function(m, fileName) {
        var imagePath = path.join(path.dirname(config.errorHtmlFile), fileName);
        return 'src="data:image/'+path.extname(fileName).substr(1)+';base64,' + fs.readFileSync(imagePath).toString('base64') + '"';
      });

      proxyFailErrorHandler = function (err, req, res) {
        res.writeHead(500, {
          'Content-Type': 'text/html'
        });
        res.write(content);
        res.end();
      };
    }

		return new DispatchTable({
			config: config.router,
			requestHandler: function(req, res, next, target) {
				req.connection.proxy = proxy;
				req.next = next;
				if(req.pathMatch || req.hostMatch) {
					target = url.parse(regexpHelper(target.href, req.hostMatch, req.pathMatch));
//					req.url = target.path;
				}
				proxy.web(req, res, {target: target});
			},
			upgradeHandler: function(req, socket, head, target) {
				if(req.pathMatch || req.hostMatch) {
					target = url.parse(regexpHelper(target.href, req.hostMatch, req.pathMatch));
	//				req.url = target.path;
				}
				proxy.ws(req, socket, head, {target: target});
			},
			entryParser: function(entryKey, entry) {
				return [entryKey,  parseEntry(entry)];
			},
			port: config.port
		});
		}
};
@@ -287,24 +287,32 @@
 ry(entry) %7B%0A
+%09var m;%0A
 %09if(typeof e
@@ -329,16 +329,16 @@
 umber')%0A
-
 %09%09entry 
@@ -394,16 +394,21 @@
  %7B%0A%09%09if(
+(m = 
 entry.ma
@@ -429,16 +429,17 @@
 /.*)$/))
+)
  %7B%0A%09%09%09en
@@ -488,17 +488,17 @@
 y.match(
-'
+/
 https?%5C/
@@ -499,17 +499,17 @@
 tps?%5C/%5C/
-'
+/
 )) %7B%0A%09%09%09
@@ -542,16 +542,51 @@
 %0A%09%09%7D%0A%09%7D%0A
+%09var withPath = entry.match(/%5C//);%0A
 %09entry =
@@ -615,16 +615,44 @@
 , true)%0A
+%09entry.withPath = withPath;%0A
 %09entry.w
@@ -1927,32 +1927,95 @@
 eq.hostMatch) %7B%0A
+%09%09%09%09%09console.log(target);%0A%09%09%09%09%09var withPath = target.withPath;%0A
 %09%09%09%09%09target = ur
@@ -2080,18 +2080,35 @@
 atch));%0A
-//
+%09%09%09%09%09if(withPath)%0A%09
 %09%09%09%09%09req
@@ -2276,24 +2276,61 @@
 ostMatch) %7B%0A
+%09%09%09%09%09var withPath = target.withPath;%0A
 %09%09%09%09%09target 
@@ -2400,18 +2400,35 @@
 tch));%0A%09
-//
+%09%09%09%09if(withPath)%0A%09%09
 %09%09%09%09req.

Fix conditional enabling of URL rewriting.