const { getSearchRequest } = require("./db/searchRequest");

const currentSearchRequest = async req => {
  const searchRequestId =
    req && req.params ? req.params["searchRequestId"] : null;
  if (!searchRequestId) return null;

  return await getSearchRequest(searchRequestId);
};

const getUrlParams = function (url) {
  if (typeof url === 'string' && url.length > 0){
    const params = {};
    const questionMarkIndex = url.indexOf('?');
    if (questionMarkIndex === -1) {
      return undefined;
    }
    const query = url.substring(questionMarkIndex+1);
    const vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split('=');
      params[pair[0]] = decodeURIComponent(pair[1]);
    }
    return params;
  }
  return undefined;
};

module.exports = {
  currentSearchRequest,
  getUrlParams
};
