'use strict';

var Writable = require('readable-stream').Writable;
var inherits = require('util').inherits;

function BufferStream() {
	Writable.call(this, { objectMode: true });
	this.buffer = [];
	this.length = 0;
}

inherits(BufferStream, Writable);
BufferStream.prototype._write = function(chunk, enc, next) {
	if (!Buffer.isBuffer(chunk)) {
		chunk = new Buffer(chunk);
	}

	this.buffer.push(chunk);
	this.length += chunk.length;
	next();
};

module.exports = function read(stream, options, cb) {
	if (!stream) {
		throw new Error('stream argument is required');
	}

	if (typeof options === 'function') {
		cb = options;
		options = {};
	}

	if (typeof options === 'string' || options === undefined || options === null) {
		options = { encoding: options };
	}

	if (options.encoding === undefined) { options.encoding = 'utf8'; }

	if (!cb) {
		throw new Error('callback argument is required');
	}

	var sink = new BufferStream();

	sink.on('finish', function () {
		var data = Buffer.concat(this.buffer, this.length);

		if (options.encoding) {
			data = data.toString(options.encoding);
		}

		cb(null, data);
	});

	stream.once('error', cb);

	stream.pipe(sink);
};
