'use strict';

module.exports = SliceStream;

var Transform = require('readable-stream/transform');
var inherits = require("util").inherits;

inherits(SliceStream, Transform);

function SliceStream(opts, sliceFn) {
  if (!(this instanceof SliceStream)) {
    return new SliceStream(opts, sliceFn);
  }

  this._opts = opts;
  this._accumulatedLength = 0;
  this.sliceFn = sliceFn;

  Transform.call(this);
}

SliceStream.prototype._transform = function (chunk, encoding, callback) {
  this._accumulatedLength += chunk.length;

  if (this._accumulatedLength >= this._opts.length) {
    //todo handle more than one slice in a stream
    var offset = chunk.length - (this._accumulatedLength - this._opts.length);
    this.sliceFn(chunk.slice(0, offset), true, chunk.slice(offset));
    callback();
  } else {
    this.sliceFn(chunk);
    callback();
  }
};
