import path from "path"
import {readdir} from "fs"

import {addLocaleData} from "react-intl"
import fr from "react-intl/locale-data/fr"
import en from "react-intl/locale-data/en"

const DEFAULT_LANGUAGE = 'fr'

export function loadTranslations(langDir) {
  addLocaleData(...fr)
  addLocaleData(...en)

  var messages = {}
  readdir(langDir, (err, files) => {
    if(err) {
      console.log("Unable to load translation files.", err)
    }

    files.forEach(file => {
      messages[path.basename(file, '.json')] = require(path.resolve(langDir, file))
    })
  })

  return messages
}

export function getLocale(acceptLanguage, messages){
  var locale = acceptLanguage ? acceptLanguage.substring(0, 2) : DEFAULT_LANGUAGE //ex: en-US;q=0.4,fr-FR;q=0.2 > en

  if(! messages[locale]) {
    locale = DEFAULT_LANGUAGE
  }
  return locale
}

export function getLocaleMessages(locale, messages){
  return messages[locale]
}

@@ -89,94 +89,8 @@
 ntl%22
-%0Aimport fr from %22react-intl/locale-data/fr%22%0Aimport en from %22react-intl/locale-data/en%22
 %0A%0Aco
@@ -166,55 +166,8 @@
 ) %7B%0A
-  addLocaleData(...fr)%0A  addLocaleData(...en)%0A%0A
   va
@@ -300,16 +300,39 @@
 %0A    %7D%0A%0A
+    var possibleLocale%0A
     file
@@ -357,25 +357,33 @@
 %7B%0A      
-messages%5B
+possibleLocale = 
 path.bas
@@ -402,16 +402,119 @@
 '.json')
+%0A      addLocaleData(require(%60react-intl/locale-data/$%7BpossibleLocale%7D%60))%0A      messages%5BpossibleLocale
 %5D = requ

Load detected react-intl locale data