/*global module, process*/
const Buffer = require('buffer').Buffer;
const Stream = require('stream');
const util = require('util');

function DataStream(data) {
  this.buffer = Buffer(data||0);
  this.writable = true;
  this.readable = true;
  if (!data)
    return this;
  if (typeof data.pipe === 'function')
    data.pipe(this);
  else if (data.length) {
    this.writable = false;
    process.nextTick(function () {
      this.buffer = data;
      this.emit('end', data);
      this.readable = false;
      this.emit('close');
    }.bind(this));
  }
}
util.inherits(DataStream, Stream);

DataStream.prototype.write = function write(data) {
  this.buffer = Buffer.concat([this.buffer, Buffer(data)]);
  this.emit('data', data);
};

DataStream.prototype.end = function end(data) {
  if (data)
    this.write(data);
  this.emit('end', data);
  this.emit('close');
  this.writable = false;
  this.readable = false;
};

module.exports = DataStream;
