export const QUERY_PARAMS_BLACKLIST = {'tt_content': true, 'tt_medium': true};

// + is the proper escape-sequence for a space-character
// within the query string component.
// See https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
function replacePlusWithEncodedSpace(str) {
  return str.replace(/\+/g, '%20');
}

/*
 * Parses the query-string and returns an object.
 *
 * Note that this does not attempt to handle unusual query strings that
 * contain the same key multiple times (e.g. "foo=1&foo=2"), array-like
 * parameters (e.g. "foo[]=1&foo[]=2"), or no-value parameters
 * (e.g. "foo=")
 */
export function parseQueryParams(queryString) {
  let params = {};

  queryString.split('&').forEach((pair) => {
    if (!pair.length) {
      return;
    }

    let [key, value] = pair.split('=');

    key = decodeURIComponent(key);
    if (value && value.length) {
      value = decodeURIComponent(replacePlusWithEncodedSpace(value));
    }

    params[key] = value;
  });

  return params;
}

export default function getQueryParamsFromURL() {
  let search = window.location.search;
  let queryString = search.slice(1); // remove the leading "?" char
  return parseQueryParams(queryString);
}();

export function withQueryParams(baseURL, whitelist, data) {
  let paramsString = whitelist.reduce((accum, key) => {
    let value = data[key];

    if (value) {
      let encodedKey = encodeURIComponent(key);
      let encodedValue = encodeURIComponent(value);
      return accum.concat(`${encodedKey}=${encodedValue}`);
    }

    return accum;
  }, []).join('&');

  if (paramsString) {
    return `${baseURL}?${paramsString}`;
  }

  return baseURL;
}

// trimQueryParams is used to strip out query parameters that we use for tracking purposes
export function trimQueryParams(pathString) {
  if (typeof pathString !== 'string' || !pathString) {
    return '';
  }

  let sliceIndex = pathString.indexOf('?');
  if (sliceIndex > -1) {
    const queryParams = parseQueryParams(pathString.slice(sliceIndex+1));
    for (const blacklistedKey in QUERY_PARAMS_BLACKLIST) {
      if (blacklistedKey in queryParams) {
        delete queryParams[blacklistedKey];
      }
    }

    return withQueryParams(
      pathString.slice(0, sliceIndex),
      Object.keys(queryParams),
      queryParams
    );
  }

  return pathString;
}
