import $ from "jquery"

const { LOCALES } = window.wagtailConfig

/* copied from oxyan */
export function getCookie(name) {
  let cookieValue = null
  if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';')
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim()
      // does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
        break
      }
    }
  }
  return cookieValue
}

/*
 * based on the url, this function will look in the pagetree to determine the
 * language of the url.
 *
 * 1. Check if the language is specified next to the title of the page in the
 *    page tree eg. "Home 'English'"
 * 2. If that is not the case, then look for the language switch dropdown in
 *    the pagetree at the top and check which language is selected
 */

function getActiveLocale(url) {
  const explorerItem = $(`.c-page-explorer__item a[href='${url}']`)
    .closest("div.c-page-explorer__item")
    .first()
  if (explorerItem.length) {
    const localeDescription = explorerItem.find(".c-page-explorer__meta > span:first").text()
    const localeConfig = LOCALES.find(x => x.display_name == localeDescription)
    if (localeConfig) {
      return localeConfig.code
    }
  }

  return $(".c-page-explorer__header__select option:selected").val()
}

/*
 * strip any locale defined in LANGUAGES from the url
 */

export function stripLocale(pathname, LANGUAGES) {
  const codes = LANGUAGES.map(([code]) => code)
  const normalizedPath = pathname.slice(1)
  for (let i = 0; i < codes.length; i++) {
    if (normalizedPath.startsWith(codes[i])) {
      return normalizedPath.slice(codes[i].length)
    }
  }
  return pathname
}

/*
 * if the url is in the wrong language, based on the output of getActiveLocale,
 * correct it, assuming `prefix_default_language=False,` is set in django
 * `i18n_patterns`. That means the LANGUAGE_CODE (default language) does not get
 * a language prefix.
 */

export function translateURL(url, currentLanguage, LANGUAGE_CODE, LANGUAGES) {
  const locale = getActiveLocale(url)
  if (locale) {
    if (locale != currentLanguage) {
      if (locale == LANGUAGE_CODE) {
        return stripLocale(url, LANGUAGES)
      }
      return `/${locale}${stripLocale(url, LANGUAGES)}`
    }
  }

  return url
}
