const cartesian = require('cartesian');

/*
const getVariances = (arr, pre='') => {
  if (!arr.length)
    return pre;

  let {name, value} = arr[0];

  let ans = arr[0].options.reduce((ans, item) => {
    return ans.concat(getVariances(arr.slice(1), pre + '&' + name + '=' + item.value));
  }, []);
  return ans;
};
*/

const getFilterQSs = (filters) => {
  const initQueryVals = filters.map(({ name, value }) => (name + '=' + value)),
        initQueryString = initQueryVals.join('&');
        
  const queryVariations = filters.map(({ name, options }) => {
    return options.map(({ value }) => (name + '=' + value));
  });
  
  let queryStrings = cartesian(queryVariations);

  for (let qsi=0; qsi < queryStrings.length; ++qsi) {
    let queryString = queryStrings[qsi].join('&');
    if (queryString === initQueryString) {
      queryStrings.splice(qsi, 1);
      --qsi;
    }
    else
      queryStrings[qsi] = queryString;
  }
  

/*
  let initQueryVals = {};
  for (let filter of filters) {
      initQueryVals[filter.name] = filter.value;
  }
  
  let qsArr = getVariances(filters);
  for (let qsi in qsArr) {
    let qs = qsArr[qsi];
    let vars = qs.split('&');
    let matching = false;
    for (var i = 0; i < vars.length; i++) {
      let pair = vars[i].split('=');
      if (initQueryVals[pair[0]] !== pair[1]) {
        matching = false;
        break;
      }
      else
        matching = true;
    }
    if (matching) {
      qsArr.splice(qsi, i);
      break;
    }
  }
  */
  
  return queryStrings;
};

module.exports = getFilterQSs;