"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FileWithEmbeddedBlockMapDifferentialDownloader = void 0;

function _bluebirdLst() {
  const data = require("bluebird-lst");

  _bluebirdLst = function () {
    return data;
  };

  return data;
}

function _fsExtraP() {
  const data = require("fs-extra-p");

  _fsExtraP = function () {
    return data;
  };

  return data;
}

function _DifferentialDownloader() {
  const data = require("./DifferentialDownloader");

  _DifferentialDownloader = function () {
    return data;
  };

  return data;
}

const pako = require("pako");

class FileWithEmbeddedBlockMapDifferentialDownloader extends _DifferentialDownloader().DifferentialDownloader {
  download() {
    var _this = this;

    return (0, _bluebirdLst().coroutine)(function* () {
      const packageInfo = _this.blockAwareFileInfo;
      const fileSize = packageInfo.size;
      const offset = fileSize - (packageInfo.blockMapSize + 4);
      _this.fileMetadataBuffer = yield _this.readRemoteBytes(offset, fileSize - 1);
      const newBlockMap = readBlockMap(_this.fileMetadataBuffer.slice(0, _this.fileMetadataBuffer.length - 4));
      yield _this.doDownload((yield readEmbeddedBlockMapData(_this.options.oldFile)), newBlockMap);
    })();
  }

}

exports.FileWithEmbeddedBlockMapDifferentialDownloader = FileWithEmbeddedBlockMapDifferentialDownloader;

function readBlockMap(data) {
  return JSON.parse(pako.inflateRaw(data, {
    to: "string"
  }));
}

function readEmbeddedBlockMapData(_x) {
  return _readEmbeddedBlockMapData.apply(this, arguments);
} function _readEmbeddedBlockMapData() {
  _readEmbeddedBlockMapData = (0, _bluebirdLst().coroutine)(function* (file) {
    const fd = yield (0, _fsExtraP().open)(file, "r");

    try {
      const fileSize = (yield (0, _fsExtraP().fstat)(fd)).size;
      const sizeBuffer = Buffer.allocUnsafe(4);
      yield (0, _fsExtraP().read)(fd, sizeBuffer, 0, sizeBuffer.length, fileSize - sizeBuffer.length);
      const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0));
      yield (0, _fsExtraP().read)(fd, dataBuffer, 0, dataBuffer.length, fileSize - sizeBuffer.length - dataBuffer.length);
      yield (0, _fsExtraP().close)(fd);
      return readBlockMap(dataBuffer);
    } catch (e) {
      yield (0, _fsExtraP().close)(fd);
      throw e;
    }
  });
  return _readEmbeddedBlockMapData.apply(this, arguments);
}
// __ts-babel@6.0.4
//# sourceMappingURL=FileWithEmbeddedBlockMapDifferentialDownloader.js.map