'use strict';

var _serverlessIndex;

function _load_serverlessIndex() {
  return _serverlessIndex = _interopRequireDefault(require('./serverless-index'));
}

var _queryBuilder;

function _load_queryBuilder() {
  return _queryBuilder = _interopRequireDefault(require('./query-builder'));
}

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

var numOfResultsPerPage = 15;

// function totalHits(index: Promise<any>, query: string) {
//   return new Promise((resolve, reject) => {
//     return index.then((indexInstance) => {
//       indexInstance.totalHits({
//         query: buildQuery(query)
//       }, (err, count) => {
//         if (err) reject(err);
//         resolve(JSON.stringify(count));
//       });
//     });
//   });
// }

// function countDocs(index: Promise<any>) {
//   return new Promise((resolve, reject) => {
//     return index.then((indexInstance) => {
//       indexInstance.countDocs((err, info) => {
//         if (err) reject(err);
//         resolve(info);
//       });
//     });
//   });
// }

// function getDoc(index: Promise<any>, docIds: string[]) {
//   return new Promise((resolve, reject) => {
//     return index.then((indexInstance) => {
//       indexInstance.get(docIds).on('data', function (doc) {
//         // console.log(doc);
//       });
//     });
//   });
// }

/**
 * Sort by the score. If the score is equal, sort by the length of the name.
 * @param {Array<any>} results
 * @return {Array<any>}
 */
function sortSearchResults(results) {
  return results.sort(function (a, b) {
    if (a.score !== b.score) return a.score - b.score;
    return a.document.name.length - b.document.name.length;
  });
}

function formatter(doc) {
  // $FlowFixMe
  if (doc.owner && typeof doc.owner === 'string' && typeof doc.scope === 'string') {
    // from web search
    return `> ${doc.owner}.${doc.scope}/${doc.box}/${doc.name}`;
  }
  return `> ${doc.box}/${doc.name}`;
}

/**
 * Search in a local LevelUp index.
 *
 * @param {string} queryStr
 * @param {string} path
 * @return {Promise}
 */
function search(queryStr, path) {
  return new Promise(function (resolve) {
    var index = (_serverlessIndex || _load_serverlessIndex()).default.initializeIndex(path);
    var searchResults = [];
    var query = (0, (_queryBuilder || _load_queryBuilder()).default)(queryStr);
    return index.then(function (indexInstance) {
      indexInstance.search({
        query,
        pageSize: numOfResultsPerPage
      }).on('data', function (data) {
        searchResults.push(data);
      }).on('end', function () {
        var searchResultsSorted = sortSearchResults(searchResults);
        return resolve(searchResultsSorted.map(function (result) {
          return result.document;
        }));
      });
    });
  });
}

module.exports = {
  search,
  formatter
};