'use strict'

var shimmer = require('shimmer')
var debug = require('debug')('opbeat')

module.exports = function (https, agent) {
  debug('shimming https.request function')

  shimmer.wrap(https, 'request', function (orig, name) {
    return function () {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to https.request %o', { uuid: uuid })

      var req = orig.apply(this, arguments)
      if (!trace) return req
      if (req._headers.host === agent._apiHost) {
        debug('ignore http request to opbeat server %o', { uuid: uuid })
        return req
      } else {
        debug('detected host: %s %o', req._headers.host, { uuid: uuid })
      }

      var name = req.method + ' ' + req._headers.host
      trace.start(name, 'ext.https.http')
      req.on('response', onresponse)

      return req

      function onresponse (res) {
        debug('intercepted http.ClientRequest response event %o', { uuid: uuid })
        res.on('end', function () {
          debug('intercepted http.IncomingMessage end event %o', { uuid: uuid })
          trace.end()
        })
      }
    }
  })

  return https
}

@@ -80,16 +80,56 @@
 beat')%0A%0A
+var SERVER_FNS = %5B'on', 'addListener'%5D%0A%0A
 module.e
@@ -163,16 +163,1282 @@
 gent) %7B%0A
+  debug('shimming https.Server.prototype functions:', SERVER_FNS)%0A%0A  shimmer.massWrap(https.Server.prototype, SERVER_FNS, function (orig, name) %7B%0A    return function (event, listener) %7B%0A      if (event === 'request' && typeof listener === 'function') return orig.call(this, event, onRequest)%0A      else return orig.apply(this, arguments)%0A%0A      function onRequest (req, res) %7B%0A        debug('intercepted call to https.Server.prototype.%25s', name)%0A%0A        var trans = agent.startTransaction(null, 'web.https')%0A        trans.req = req%0A%0A        res.once('finish', function () %7B%0A          if (!trans._defaultName) %7B%0A            var path%0A%0A            // Get proper route name from Express 4.x%0A            if (req.route) %7B%0A              path = req.route.path %7C%7C req.route.regexp && req.route.regexp.source%0A            %7D%0A%0A            if (!path) %7B%0A              debug('could not extract route name from request %25o', %7B url: req.url, uuid: trans._uuid %7D)%0A              path = 'unknown route'%0A            %7D%0A%0A            trans.setDefaultName(req.method + ' ' + path)%0A          %7D%0A%0A          trans.result = res.statusCode%0A          debug('ending transaction %25o', %7B uuid: trans._uuid %7D)%0A          trans.end()%0A        %7D)%0A%0A        listener.apply(this, arguments)%0A      %7D%0A    %7D%0A  %7D)%0A%0A
   debug(

Support automatic tracing of https servers