import * as qs from 'query-string'

export function getParameter(name: string, locationSearch: string) {
  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
  var results = regex.exec(locationSearch)
  return results === null
    ? ''
    : decodeURIComponent(results[1].replace(/\+/g, ' '))
}

export function extendSearchParams(search: string, params: Object) {
  const existingParams = qs.parse(search)
  return stringifyParams({ ...existingParams, ...params })
}

export function parseQuery(query: string) {
  let params: any = qs.parse(query)
  if (params['term']) {
    params['term'] = decodeSearchTerm(params['term'])
  }
  return params
}

export function stringifyParams(params: any) {
  const encodedParams: any = {}

  Object.keys(params).forEach(key => {
    if (params[key] === undefined || params[key] === null) {
      // skip assignment
    } else if (key === 'namespace' && params[key] === 'none') {
      // skip assignment
    } else if (key === 'term') {
      encodedParams[key] = encodeSearchTerm(params[key])
    } else {
      encodedParams[key] = encodeURIComponent(params[key])
    }
  })

  return qs.stringify(encodedParams, { encode: false })
}

export function encodeSearchTerm(term: string) {
  return term
    .split(' ')
    .map(encodeURIComponent)
    .join('+')
}

export function decodeSearchTerm(encodedTerm: string) {
  return decodeURIComponent(encodedTerm)
    .split('+')
    .map(decodeURIComponent)
    .join(' ')
}
