import { reactive } from 'vue'

export const modulesParse = (modules: Record<string, () => Promise<any>>) => {
  const ctx: any = reactive({})
  const requests = Promise.all(Object.values(modules).map(fn => fn()))

  return {
    ctx,
    promise: requests.then((cts: any[]) => {
      const keys = Object.keys(modules)
      const lang = Object.fromEntries(keys.map((key, i) => [key, cts[i]]))
      langMessageFactory(lang, 'lang', ctx)
    })
  }
}

export function langMessageFactory(
  requireModules: { [key in string]: any },
  prefix = 'lang',
  lang: { [key in string]: any } = {}
) {
  const filenames = Object.keys(requireModules)

  for (let filename of filenames) {
    const langAtom = requireModules[filename].default

    filename = filename.replace(`./${prefix}/`, '').replace(/^\.\//, '')
    filename = filename.substring(0, filename.lastIndexOf('.'))

    const locals = filename.split('/')
    const langname = locals.pop()
    let current = lang

    for (const name of locals) {
      lang[name] = current = lang[name] || {}
    }
    current[langname!] = langAtom
  }

  return lang
}
