'use strict'

/**
 * Code imported from `pino-http`
 * Repo: https://github.com/pinojs/pino-http
 * License: MIT (https://raw.githubusercontent.com/pinojs/pino-http/master/LICENSE)
 */

const pino = require('pino')

function createLogger (opts, stream) {
  stream = stream || opts.stream
  delete opts.stream

  var prevLogger = opts.logger
  var prevGenReqId = opts.genReqId
  var logger = null

  if (prevLogger) {
    opts.logger = undefined
    opts.genReqId = undefined
    logger = prevLogger.child(opts)
    opts.logger = prevLogger
    opts.genReqId = prevGenReqId
  } else {
    logger = pino(opts, stream)
  }

  return logger
}

function reqIdGenFactory () {
  var maxInt = 2147483647
  var nextReqId = 0
  return function genReqId () {
    return (nextReqId = (nextReqId + 1) & maxInt)
  }
}

const serializers = {
  req: function asReqValue (req) {
    return {
      id: req.id,
      method: req.method,
      url: req.url,
      remoteAddress: req.connection.remoteAddress,
      remotePort: req.connection.remotePort
    }
  },
  err: function asErrValue (err) {
    var obj = {
      type: err.constructor.name,
      message: err.message,
      stack: err.stack
    }
    for (var key in err) {
      if (obj[key] === undefined) {
        obj[key] = err[key]
      }
    }
    return obj
  },
  res: function asResValue (res) {
    return {
      statusCode: res.statusCode
    }
  }
}

function OnResponseState (err, res) {
  this.err = err
  this.res = res
}

function onResponseIterator (fn, cb) {
  fn(this.res, cb)
}

function now () {
  var ts = process.hrtime()
  return (ts[0] * 1e3) + (ts[1] / 1e6)
}

function onResponseCallback (err, res) {
  var responseTime = now() - res._startTime

  if (err) {
    res.log.error({
      res,
      err,
      responseTime
    }, 'request errored')
    return
  }

  res.log.info({
    res,
    responseTime
  }, 'request completed')
}

module.exports = {
  createLogger,
  reqIdGenFactory,
  serializers,
  now,
  OnResponseState,
  onResponseIterator,
  onResponseCallback
}

@@ -1049,266 +1049,31 @@
 rr: 
-function asErrValue (err) %7B%0A    var obj = %7B%0A      type: err.constructor.name,%0A      message: err.message,%0A      stack: err.stack%0A    %7D%0A    for (var key in err) %7B%0A      if (obj%5Bkey%5D === undefined) %7B%0A        obj%5Bkey%5D = err%5Bkey%5D%0A      %7D%0A    %7D%0A    return obj%0A  %7D
+pino.stdSerializers.err
 ,%0A  

use pino default error serializer