// Generated by CoffeeScript 1.7.1

/*
PDFReference - represents a reference to another object in the PDF object heirarchy
By Devon Govett
 */

(function() {
  var PDFObject, PDFReference, zlib,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  zlib = require('zlib');

  PDFReference = (function() {
    function PDFReference(document, id, data) {
      this.document = document;
      this.id = id;
      this.data = data != null ? data : {};
      this.finalize = __bind(this.finalize, this);
      this.gen = 0;
      this.deflate = null;
      this.compress = this.document.compress && !this.data.Filter;
      this.uncompressedLength = 0;
      this.chunks = [];
    }

    PDFReference.prototype.initDeflate = function() {
      this.data.Filter = 'FlateDecode';
      this.deflate = zlib.createDeflate();
      this.deflate.on('data', (function(_this) {
        return function(chunk) {
          _this.chunks.push(chunk);
          return _this.data.Length += chunk.length;
        };
      })(this));
      return this.deflate.on('end', this.finalize);
    };

    PDFReference.prototype.write = function(chunk) {
      var _base;
      if (!Buffer.isBuffer(chunk)) {
        chunk = new Buffer(chunk + '\n', 'binary');
      }
      this.uncompressedLength += chunk.length;
      if ((_base = this.data).Length == null) {
        _base.Length = 0;
      }
      if (this.compress) {
        if (!this.deflate) {
          this.initDeflate();
        }
        return this.deflate.write(chunk);
      } else {
        this.chunks.push(chunk);
        return this.data.Length += chunk.length;
      }
    };

    PDFReference.prototype.end = function(chunk) {
      if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
        this.write(chunk);
      }
      if (this.deflate) {
        return this.deflate.end();
      } else {
        return this.finalize();
      }
    };

    PDFReference.prototype.finalize = function() {
      var chunk, _i, _len, _ref;
      this.offset = this.document._offset;
      this.document._write("" + this.id + " " + this.gen + " obj");
      this.document._write(PDFObject.convert(this.data));
      if (this.chunks.length) {
        this.document._write('stream');
        _ref = this.chunks;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          chunk = _ref[_i];
          this.document._write(chunk);
        }
        this.chunks.length = 0;
        this.document._write('\nendstream');
      }
      this.document._write('endobj');
      return this.document._refEnd(this);
    };

    PDFReference.prototype.toString = function() {
      return "" + this.id + " " + this.gen + " R";
    };

    return PDFReference;

  })();

  module.exports = PDFReference;

  PDFObject = require('./object');

}).call(this);
