'use strict';

module.exports = init;

var debug = require('debug')('swagger:hapi_middleware');

function init(runner) {
  return new Hapi(runner);
}

function Hapi(runner) {
  this.runner = runner;
  this.config = runner.config;
  this.sysConfig = runner.config.swagger;

  var connectMiddleware = runner.connectMiddleware();
  var chain = connectMiddleware.middleware();

  this.register = function(app, cb) {
    app.register(this.plugin, cb);
  };

  this.plugin = {
    register: function(server, options, next) {

      server.ext('onRequest', function(request, reply) {

        var req = request.raw.req;
        var res = newResponse(reply);

        chain(req, res, function(err) {
          if (err) { return next(err); }
          res.finish();
        });
      });

      server.on('request-error', function (request, err) {
        debug('Request: %s error: %s', request.id, err.stack);
      });

      next();
    }
  };
  this.plugin.register.attributes = { name: 'swagger-node-runner', version: version() };
}

function version() {
  return require('../package.json').version;
}

function newResponse(reply) {
  var statusCode = 200;
  var headers = {};
  var res;
  return {
    getHeader: function(name) {
      return headers[name.toLowerCase()];
    },
    setHeader: function(name, value) {
      headers[name.toLowerCase()] = value;
    },
    end: function(string) {
      res = reply(string);
      res.statusCode = statusCode;
      for (var header in headers) {
        res.header(header, headers[header]);
      }
    },
    finish: function() {
      if (!res) {
        reply.continue();
      }
    }
  };
}

@@ -226,50 +226,8 @@
 fig;
-%0A  this.sysConfig = runner.config.swagger;
 %0A%0A  
@@ -1084,63 +1084,8 @@
 ) %7B%0A
-  var statusCode = 200;%0A  var headers = %7B%7D;%0A  var res;%0A
   re
@@ -1135,16 +1135,31 @@
   return
+ this.headers ?
  headers
@@ -1178,16 +1178,23 @@
 rCase()%5D
+ : null
 ;%0A    %7D,
@@ -1239,16 +1239,69 @@
 %7B%0A      
+if (!this.headers) %7B this.headers = %7B%7D; %7D%0A      this.
 headers%5B
@@ -1370,16 +1370,21 @@
 %7B%0A      
+this.
 res = re
@@ -1398,24 +1398,29 @@
 ing);%0A      
+this.
 res.statusCo
@@ -1424,16 +1424,21 @@
 sCode = 
+this.
 statusCo
@@ -1441,16 +1441,44 @@
 usCode;%0A
+      if (this.headers) %7B%0A  
       fo
@@ -1494,16 +1494,21 @@
 ader in 
+this.
 headers)
@@ -1514,24 +1514,31 @@
 ) %7B%0A        
+  this.
 res.header(h
@@ -1544,16 +1544,21 @@
 header, 
+this.
 headers%5B
@@ -1567,16 +1567,26 @@
 ader%5D);%0A
+        %7D%0A
       %7D%0A
@@ -1628,16 +1628,21 @@
    if (!
+this.
 res) %7B%0A 

fix Hapi