'use strict';

const q = require("q");
const _ = require("lodash/string");
let searchService = null;

const initOptions = (options) => {
  if (!options) {
    options = {};
  }
  return options;
};

const getDataSource = (options) =>{

  let providerPath;

  options = initOptions(options);
  let connName = options.connectionName ? options.connectionName : "defaultSearch";
  options.connectionName = connName;

  const dbConfig = require('../database/providers/DatabaseConfig');
  let dsConfig = dbConfig.getDataServicesConfig(connName);
  if (dsConfig && dsConfig.providerName){
    providerPath = "./" + _.capitalize(_.camelCase(dsConfig.providerName)) + "SearchService";
  }
  else{
    providerPath = "./ElasticSearchService";
  }

  return require(providerPath);
};

const generatePit = () => {
  const elasticSearchService = require('./ElasticSearchService');
  return elasticSearchService.generatePit();
};

const search = (query, userId, allVersions, options) => {
  options = initOptions(options);
  if (query && query.connectionName) {
    options.connectionName = query.connectionName;
  }
  searchService = getDataSource(options);

  const searchFunc =searchService.search;
  return searchFunc(query, userId, allVersions, options);

};

module.exports = {
  search: search,
  getDataSource: getDataSource,
  generatePit
};
