import { useEffect, useCallback } from 'react'

import isEmpty from 'lodash/isEmpty'

import { getLexics } from 'requests'

import {
  getLexicIds,
  mapTranslationsToLocalKeys,
} from 'features/LexicsStore/helpers'

import { useLang } from './useLang'
import { useLexicsConfig } from './useLexicsConfig'
import { useTranslations } from './useTranslations'

export const useLexics = () => {
  const { changeLang, lang } = useLang()
  const { addLexicsConfig, lexicsConfig } = useLexicsConfig()
  const { addTranslations, translate } = useTranslations()

  const fetchLexics = useCallback(
    async () => {
      const lexicIds = getLexicIds(lexicsConfig)
      if (isEmpty(lexicIds)) return

      const newTranslations = await getLexics(lang, lexicIds)
      addTranslations(mapTranslationsToLocalKeys(newTranslations, lexicsConfig))
    },
    [
      lang,
      lexicsConfig,
      addTranslations,
    ],
  )

  useEffect(() => {
    fetchLexics()
  }, [
    lang,
    lexicsConfig,
    fetchLexics,
  ])

  return {
    addLexicsConfig,
    changeLang,
    lang,
    translate,
  }
}
