import { computed, createApp, watchEffect } from 'vue'
import App from './app.vue'
import axios from 'axios'
import { langs, deflangName, loaded } from '@/lang'

export type Lang = {
  [key in string]: string | Lang
}

document.title = '国际化文件配置'

const deflang = langs[deflangName]
const normalLangs = (lang: any, standard: any) => {
  lang = { ...lang }
  for (const key in standard) {
    const exists1 = key in lang
    const exists2 = key in standard
    const type1 = typeof lang[key]
    const type2 = typeof standard[key]

    if (exists1 !== exists2 || type1 !== type2) {
      lang[key] = standard[key]
    } else if (type1 !== 'string') {
      lang[key] = normalLangs(lang[key], standard[key])
    }
  }
  return lang
}

const stopWatch = watchEffect(() => {
  if (loaded.value) {
    const nlangs = Object.entries(langs)
      .map(([name, value]) => [
        name,
        deflang === value ? value : normalLangs(value, deflang)
      ])
      .reduce((t, [name, lang]) => {
        ;(t as any)[name] = lang
        return t
      }, {})

    const app = createApp(App, {
      langs: nlangs,
      onSubmit() {
        axios.post('/dev/langs', nlangs)
        console.log(nlangs)
      }
    })
    app.mount('#app')
    stopWatch()
  }
})
