'use strict';
var createHash = require('create-hash/browser');
var Transform = require('stream').Transform;
var inherits = require('inherits')
var zeroBuffer = new Buffer(128)
zeroBuffer.fill(0)

module.exports = Hmac
inherits(Hmac, Transform)
function Hmac (alg, key) {
  if(!(this instanceof Hmac)) return new Hmac(alg, key)

  Transform.call(this)
  this._opad = opad
  this._alg = alg

  var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64

  key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key

  if(key.length > blocksize) {
    key = createHash(alg).update(key).digest()
  } else if(key.length < blocksize) {
    key = Buffer.concat([key, zeroBuffer], blocksize)
  }

  var ipad = this._ipad = new Buffer(blocksize)
  var opad = this._opad = new Buffer(blocksize)

  for(var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  this._hash = createHash(alg).update(ipad)
}

Hmac.prototype.update = function (data, enc) {
  this.write(data, enc)
  return this
}

Hmac.prototype._transform = function (data, _, next) {
  this._hash.update(data)
  next()
}

Hmac.prototype._flush = function (next) {
  var h = this._hash.digest()
  this.push(createHash(this._alg).update(this._opad).update(h).digest())
  next()
}

Hmac.prototype.digest = function (enc) {
  this.end()
  var outData = new Buffer('')
  var chunk
  while ((chunk = this.read())) {
    outData = Buffer.concat([outData, chunk])
  }
  if (enc) {
    outData = outData.toString(enc)
  }
  return outData
}
