import isNull from 'lodash/isNull'

import { history } from 'config/history'
import { client } from 'config/clients'
import { checkCookie } from '../cookie'

const KEY = 'lang'

export const getLanguageUrlParam = () => {
  const lang = new URLSearchParams(history.location.search).get(KEY)
  return (lang !== 'null' && !isNull(lang)) ? lang : client.defaultLanguage
}

export const addLanguageUrlParam = (lang: string, url: string) => {
  const urlObject = new URL(url)
  urlObject.searchParams.set(KEY, lang)
  return urlObject.toString()
}

export const addAccessTokenToUrl = (url: string) => {
  const urlObject = new URL(url)
  const token = checkCookie('access_token')?.split('=')
  token && urlObject.searchParams.set(token[0], token[1])
  return urlObject.toString()
}
