/**
 * node-archiver
 *
 * Copyright (c) 2012-2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/archiverjs/node-archiver/blob/master/LICENSE-MIT
 */
var zlib = require('zlib');

var engine = require('tar-stream');
var util = require('../util');

var Tar = module.exports = function(options) {
  if (!(this instanceof Tar)) {
    return new Tar(options);
  }

  options = this.options = util.defaults(options, {
    gzip: false
  });

  if (typeof options.gzipOptions !== 'object') {
    options.gzipOptions = {};
  }

  this.supports = {
    directory: true
  };

  this.engine = engine.pack(options);
  this.compressor = false;

  if (options.gzip) {
    this.compressor = zlib.createGzip(options.gzipOptions);
    this.compressor.on('error', this._onCompressorError.bind(this));
  }
};

Tar.prototype._onCompressorError = function(err) {
  this.engine.emit('error', err);
};

Tar.prototype.append = function(source, data, callback) {
  var self = this;

  data.mtime = data.date;

  function append(err, sourceBuffer) {
    if (err) {
      callback(err);
      return;
    }

    self.engine.entry(data, sourceBuffer, function(err) {
      callback(err, data);
    });
  }

  if (data.sourceType === 'buffer') {
    append(null, source);
  } else if (data.sourceType === 'stream' && data._stats) {
    data.size = data._stats.size;

    var entry = self.engine.entry(data, function(err) {
      callback(err, data);
    });

    source.pipe(entry);
  } else if (data.sourceType === 'stream') {
    util.collectStream(source, append);
  }
};

Tar.prototype.finalize = function() {
  this.engine.finalize();
};

Tar.prototype.on = function() {
  return this.engine.on.apply(this.engine, arguments);
};

Tar.prototype.pipe = function(destination, options) {
  if (this.compressor) {
    return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options);
  } else {
    return this.engine.pipe.apply(this.engine, arguments);
  }
};

Tar.prototype.unpipe = function() {
  if (this.compressor) {
    return this.compressor.unpipe.apply(this.compressor, arguments);
  } else {
    return this.engine.unpipe.apply(this.engine, arguments);
  }
};