'use strict';

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

var initializeIndex = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(scopePath) {
    var indexOptions;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!index) {
              // static var to make sure the index is not instantiated twice
              indexOptions = {
                indexPath: getIndexPath(scopePath),
                logLevel,
                stopwords: []
              };


              index = new Promise(function (resolve, reject) {
                (0, (_searchIndex || _load_searchIndex()).default)(indexOptions, function (err, si) {
                  if (err) reject(err);
                  resolve(si);
                });
              });
            }

            return _context.abrupt('return', index);

          case 2:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

  return function initializeIndex(_x) {
    return _ref.apply(this, arguments);
  };
}();

var _path;

function _load_path() {
  return _path = _interopRequireDefault(require('path'));
}

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _searchIndex;

function _load_searchIndex() {
  return _searchIndex = _interopRequireDefault(require('search-index'));
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../logger/logger'));
}

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

var indexName = 'search_index';
var logLevel = 'error';
var index = void 0;

function getIndexPath(scopePath) {
  return (_path || _load_path()).default.join(scopePath, indexName);
}

function deleteDb(scopePath) {
  var indexPath = getIndexPath(scopePath);
  (_logger || _load_logger()).default.debug(`deleting index-search at ${indexPath}`);
  if (!scopePath || !indexPath) return;
  (_fsExtra || _load_fsExtra()).default.removeSync(indexPath);
}

module.exports = {
  deleteDb,
  getIndexPath,
  initializeIndex
};