"use strict";

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

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _rimraf = _interopRequireDefault(require("rimraf"));

var _unzipCrx = _interopRequireDefault(require("unzip-crx-3"));

var _utils = require("./utils");

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

var downloadChromeExtension = function downloadChromeExtension(chromeStoreID, forceDownload) {
  var attempts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 5;
  var extensionsStore = (0, _utils.getPath)();

  if (!_fs["default"].existsSync(extensionsStore)) {
    _fs["default"].mkdirSync(extensionsStore, {
      recursive: true
    });
  }

  var extensionFolder = _path["default"].resolve("".concat(extensionsStore, "/").concat(chromeStoreID));

  return new Promise(function (resolve, reject) {
    if (!_fs["default"].existsSync(extensionFolder) || forceDownload) {
      if (_fs["default"].existsSync(extensionFolder)) {
        _rimraf["default"].sync(extensionFolder);
      }

      var fileURL = "https://clients2.google.com/service/update2/crx?response=redirect&acceptformat=crx2,crx3&x=id%3D".concat(chromeStoreID, "%26uc&prodversion=32"); // eslint-disable-line

      var filePath = _path["default"].resolve("".concat(extensionFolder, ".crx"));

      (0, _utils.downloadFile)(fileURL, filePath).then(function () {
        (0, _unzipCrx["default"])(filePath, extensionFolder).then(function () {
          (0, _utils.changePermissions)(extensionFolder, 755);
          resolve(extensionFolder);
        })["catch"](function (err) {
          if (!_fs["default"].existsSync(_path["default"].resolve(extensionFolder, 'manifest.json'))) {
            return reject(err);
          }
        });
      })["catch"](function (err) {
        console.log("Failed to fetch extension, trying ".concat(attempts - 1, " more times")); // eslint-disable-line

        if (attempts <= 1) {
          return reject(err);
        }

        setTimeout(function () {
          downloadChromeExtension(chromeStoreID, forceDownload, attempts - 1).then(resolve)["catch"](reject);
        }, 200);
      });
    } else {
      resolve(extensionFolder);
    }
  });
};

var _default = downloadChromeExtension;
exports["default"] = _default;