'use strict';
var async = require('async');
const _ = require("lodash/object");

const processSearchResults = (results, elementProcessingCallback, completionCallback  ) => {
      let docs = [];
      const isOtherSearch = (results.searchProvier && results.searchProvier !== "elastic");
      let resultDocs;
      let totalHits = 0;
      if (isOtherSearch) {
        resultDocs = results.data;
        totalHits = results.total ?  results.total : results.data.length;
      }
      else {
        resultDocs = results.data.hits.hits;
        totalHits = results.data.hits.total;
      }

      async.eachSeries(resultDocs, function (hit, next){
        let doc;
        if (isOtherSearch){
          //if alias is not given in the select statement, then the result enclosed with bucketName / db Name.
          const objKeys = Object.keys(hit);
          if (objKeys.length <= 1 && results.dbName === objKeys[0]){
            doc = _.omit(hit[objKeys], ['total_hits']);
          }
          else{
            doc = _.omit(hit, ['total_hits']);
          }
        }
        else{
          doc = hit._source;
        }

        elementProcessingCallback(doc);
        docs.push(doc);
        next();
      }, function(err) {
        if (err){
          logger.error("Error in processing search results : " + JSON.stringify(err));
        }
        completionCallback(docs, totalHits);
      });
};


exports.processSearchResults = processSearchResults;
