"use strict";

var SharedConstants = require('../../shared/constants/SharedConstants');
var SearchService = require('../search/SearchService');
var UtilElasticSearch = require('../utils/UtilElasticSearch');

function findByElastic(query, userId, searchContext, callback) {
    var options = searchContext ? searchContext : {};
    options.page = SharedConstants.DEFAULT_PAGE;
    options.pageSize = SharedConstants.DEFAULT_TOTAL_ITEM;
    options.filter = query;

    SearchService.search(options, userId).then(
        function successFunc(data) {
            if (searchContext && searchContext.shouldExtractSource) {
                var list = data.data.hits.hits;
                var returnedList = [];
                for (var i = 0; i < list.length; i++) {
                    returnedList.push(list[i]._source);
                }
                callback(null, returnedList);
            } else {
                callback(null, data);
            }
        }, function errorFunc(err) {
            if (typeof err === 'string') {
                err = {
                    message: err
                };
            }
            
            callback(err);
        }
    );
};

module.exports = {
    findByElastic: findByElastic
};