import { parseId } from '../../lib/numberUtil';

export function pagedAndSortedLocation(location, linkId, sort, newFilters) {
  return { ...location,
    query: {
      ...location.query,
      linkId,
      sort,
      ...newFilters,
    } };
}

export function pagedLocation(location, linkId) {
  return { ...location,
    query: {
      ...location.query,
      linkId,
    } };
}

export function filteredLocation(location, filters) {
  return { ...location,
    query: {
      ...location.query,
      ...filters,
    } };
}

export function filteredLinkTo(to, filters, baseQuery) {
  let query = baseQuery || {};
  // don't add filters if there are none
  if (filters.snapshotId || parseId(filters.timespanId) || parseId(filters.focusId) || filters.q) {
    query = {
      snapshotId: parseId(filters.snapshotId),
      timespanId: parseId(filters.timespanId),
      focusId: parseId(filters.focusId),
      q: filters.q,
      ...query,
    };
  }
  return { pathname: to, query };
}

export function combineQueryParams(filterQ, query) {
  if (filterQ) {
    return `${filterQ} AND ${query}`;
  }
  if (query) {
    return query;
  }
  return undefined;
}

export function formatAsUrlParams(params) {
  // https://stackoverflow.com/questions/7045065/how-do-i-turn-a-javascript-dictionary-into-an-encoded-url-string
  return Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${(v === null || v === undefined) ? '' : encodeURIComponent(v)}`).join('&');
}


export function filtersAsUrlParams(filters) {
  const cleanedFilters = {
    snapshotId: filters.snapshotId,
    timespanId: filters.timespanId || '',
    focusId: filters.focusId || '',
    q: filters.q || '',
  };
  return formatAsUrlParams(cleanedFilters);
}

export function urlWithFilters(to, filters) {
  return `#${to}?${filtersAsUrlParams(filters)}`;
}

@@ -1045,59 +1045,66 @@
 %7B%0A  
-if (filterQ) %7B%0A    return %60$%7BfilterQ%7D AND $%7Bquery%7D%60
+const parts = %5B%5D;%0A  if (filterQ) %7B%0A    parts.push(filterQ)
 ;%0A  
@@ -1128,28 +1128,33 @@
     
-return 
+parts.push(
 query
+)
 ;%0A  %7D%0A  
 retu
@@ -1153,24 +1153,88 @@
 %7D%0A  
-return undefined
+if (parts.length === 0) %7B%0A    return undefined;%0A  %7D%0A  return parts.join(' AND ')
 ;%0A%7D%0A

Fix bad query combination sending "undefined" as a string to server