'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _zlib;

function _load_zlib() {
  return _zlib = require('zlib');
}

var _repository;

function _load_repository() {
  return _repository = _interopRequireDefault(require('./repository'));
}

var _utils;

function _load_utils() {
  return _utils = require('../../utils');
}

var _constants;

function _load_constants() {
  return _constants = require('../../constants');
}

var _ref;

function _load_ref() {
  return _ref = _interopRequireDefault(require('./ref'));
}

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// import logger from '../../logger/logger';

function parse(buffer, types) {
  var firstNullByteLocation = buffer.indexOf((_constants || _load_constants()).NULL_BYTE);
  var headers = buffer.slice(0, firstNullByteLocation).toString();
  var contents = buffer.slice(firstNullByteLocation + 1, buffer.length);

  var _headers$split = headers.split((_constants || _load_constants()).SPACE_DELIMITER),
      _headers$split2 = _slicedToArray(_headers$split, 1),
      type = _headers$split2[0];

  return types[type].parse(contents);
}

var BitObject = function () {
  function BitObject() {
    _classCallCheck(this, BitObject);

    this.validateBeforePersist = true;
  }

  _createClass(BitObject, [{
    key: 'id',
    // validate the object before persisting
    value: function id() {
      throw new Error('id() was not implemented...');
    }

    // eslint-disable-next-line no-unused-vars

  }, {
    key: 'toBuffer',
    value: function toBuffer(pretty) {
      throw new Error('toBuffer() was not implemented...');
    }

    // eslint-disable-next-line no-unused-vars

  }, {
    key: 'refs',
    value: function refs() {
      return [];
    }
  }, {
    key: 'collectRefs',
    value: function collectRefs(repo) {
      var throws = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

      var refsCollection = [];

      function addRefs(object) {
        var refs = object.refs();
        var objs = refs.map(function (ref) {
          return ref.loadSync(repo, throws);
        }).filter(function (x) {
          return x;
        });

        refsCollection.push.apply(refsCollection, _toConsumableArray(refs));
        objs.forEach(function (obj) {
          return addRefs(obj);
        });
      }

      addRefs(this);
      return refsCollection;
    }
  }, {
    key: 'collectExistingRefs',
    value: function collectExistingRefs(repo) {
      var throws = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

      var refsCollection = [];

      function addRefs(object) {
        var refs = object.refs();
        var objs = refs.map(function (ref) {
          return ref.loadSync(repo, throws);
        }).filter(function (x) {
          return x;
        });
        var filtered = refs.filter(function (ref) {
          return repo.loadSync(ref, false);
        });
        refsCollection.push.apply(refsCollection, _toConsumableArray(filtered));
        objs.forEach(function (obj) {
          return addRefs(obj);
        });
      }

      addRefs(this);
      return refsCollection;
    }
  }, {
    key: 'collectRaw',
    value: function collectRaw(repo) {
      return Promise.all(this.collectRefs(repo).map(function (ref) {
        return ref.loadRaw(repo);
      }));
    }
  }, {
    key: 'asRaw',
    value: function asRaw(repo) {
      return repo.loadRaw(this.hash());
    }
  }, {
    key: 'collect',
    value: function collect(repo) {
      var objects = [];

      function addRefs(object) {
        var objs = object.refs().map(function (ref) {
          return ref.loadSync(repo);
        });

        objects.concat(objs);
        objs.forEach(function (obj) {
          return addRefs(obj);
        });
      }

      addRefs(this);
      return objects;
    }

    /**
     * indexing method
     */

  }, {
    key: 'hash',
    value: function hash() {
      // console.log(`sha ${sha1(this.id())}, id ${this.id()}`); // uncomment when debugging hash issues
      return new (_ref || _load_ref()).default(BitObject.makeHash(this.id()));
    }
  }, {
    key: 'compress',
    value: function compress() {
      return (0, (_utils || _load_utils()).deflate)(this.serialize());
    }
  }, {
    key: 'serialize',
    value: function serialize() {
      return Buffer.concat([Buffer.from(this.header), this.toBuffer()]);
    }
  }, {
    key: 'header',
    get: function get() {
      return `${this.constructor.name} ${this.hash().toString()} ${this.toBuffer().toString().length}${(_constants || _load_constants()).NULL_BYTE}`;
    }
  }], [{
    key: 'parse',
    value: function parse(data) {
      throw new Error('parse() was not implemented...');
    }
  }, {
    key: 'parseObject',
    value: function parseObject(fileContents, types) {
      return (0, (_utils || _load_utils()).inflate)(fileContents).then(function (buffer) {
        return parse(buffer, types);
      });
    }
  }, {
    key: 'parseSync',
    value: function parseSync(fileContents, types) {
      var buffer = (0, (_zlib || _load_zlib()).inflateSync)(fileContents);
      return parse(buffer, types);
    }
  }, {
    key: 'makeHash',
    value: function makeHash(str) {
      return (0, (_utils || _load_utils()).sha1)(str);
    }
  }]);

  return BitObject;
}();

exports.default = BitObject;