var Transform = require('stream').Transform;
var parseEvent = require('./parse-event').parseEvent;

/** @type {Transform} */
function EventUnmarshallerStream(options) {
    options = options || {};
    // set output to object mode
    options.readableObjectMode = true;
    Transform.call(this, options);
    this._readableState.objectMode = true;

    this.parser = options.parser;
    this.eventStreamModel = options.eventStreamModel;
}

EventUnmarshallerStream.prototype = Object.create(Transform.prototype);

/**
 *
 * @param {Buffer} chunk
 * @param {string} encoding
 * @param {*} callback
 */
EventUnmarshallerStream.prototype._transform = function(chunk, encoding, callback) {
    try {
        var event = parseEvent(this.parser, chunk, this.eventStreamModel);
        this.push(event);
        return callback();
    } catch (err) {
        callback(err);
    }
};

/**
 * @api private
 */
module.exports = {
    EventUnmarshallerStream: EventUnmarshallerStream
};
