import { createI18n,  } from 'vue-i18n';
import fetcher from '@cloudron/pankow/fetcher.js';
import { API_ORIGIN } from './constants.js';

const translations = {};

const i18n = createI18n({
  legacy: false,
  locale: 'en',
  fallbackLocale: 'en',
  messages: translations,
  warnHtmlInMessage: 'off',
  // will replace our double {{}} to vue-i18n single brackets
  messageResolver: function (keys, key) {
    const message = key.split('.').reduce((o, k) => o && o[k] || null, keys);

    // if not found return null to fallback to resolving for english
    if (message === null) return null;

    // vue-js translation treats @ as linked data, so we have to replace them into a literal variable for now
    // https://vue-i18n.intlify.dev/guide/essentials/syntax.html#literal-interpolation
    try {
      return message.replaceAll('{{', '{').replaceAll('}}', '}').replaceAll('@', "{'@'}");
    } catch (e) {
      console.log(`Error translating key: ${key} message: ${JSON.stringify(message)}`, e);
      return '';
    }
  }
});

// https://vue-i18n.intlify.dev/guide/advanced/lazy.html
async function loadLanguage(lang) {
  try {
    const result = await fetcher.get(`${API_ORIGIN}/translation/${lang}.json`, { t: import.meta.env.VITE_CACHE_ID });
    translations[lang] = result.body;
  } catch (e) {
    console.error(`Failed to load language file for ${lang}`, e);
  }
}

async function main() {
  // load at least fallback english
  await loadLanguage('en');

  const locale = window.localStorage.NG_TRANSLATE_LANG_KEY || window.cloudron?.language;

  if (locale && locale !== 'en') {
    await loadLanguage(locale);
    i18n.global.locale.value = locale;
  }

  return i18n;
}

async function setLanguage(lang, profile = false) {
  // only change if we set the language also for the profile or the user has no profile language set
  if (profile) window.localStorage.NG_TRANSLATE_LANG_KEY = lang;
  else if (window.localStorage.NG_TRANSLATE_LANG_KEY) return;

  try {
    const result = await fetcher.get(`${API_ORIGIN}/translation/${lang}.json`, { t: import.meta.env.VITE_CACHE_ID });
    i18n.global.setLocaleMessage(lang, result.body);
  } catch (e) {
    console.error(`Failed to load language file for ${lang}`, e);
  }

  i18n.global.locale.value = lang;
}

export default main;

export {
  setLanguage
};
