import { getLanguage, getLocales, localizerFactory, setLocales } from "@uxland/localization";

/**
 * Creates a locale manager for a given plugin ID and translations.
 *
 * @param {string} pluginId - The ID of the plugin.
 * @param {Record<string, Record<string, string>>} translations - The translations for the plugin.
 * @return {Promise<{
 *   translate: (path: string, variables?: Record<string, string>) => string,
 *   getTranslations: () => Record<string, string>,
 *   getCurrentLanguage: () => string,
 * }>} A promise that resolves to an object with methods for translating strings and getting translations.
 */
export const createLocaleManager =
  (pluginId: string) => (translations: Record<string, Record<string, string>>) => {
    const localizer = localizerFactory(getLanguage(), translations, "", true);
    setLocales(translations);
    return Promise.resolve({
      /**
       * Translates the given path using the provided variables and the plugin's ID.
       *
       * @param {string} path - The path to be translated.
       * @param {Record<string, string>} [variables] - Optional variables to be used in the translation.
       * @return {string} The translated string, or the original path if an error occurs.
       */
      translate: (path: string, variables?: Record<string, string>) => {
        try {
          return localizer(`${pluginId}.${path}`, variables);
        } catch (e) {
          console.error(e);
          return path;
        }
      },
      /**
       * Retrieves the translations for the current language and plugin.
       *
       * @return {Record<string, string>} The translations for the current language and plugin.
       */
      getTranslations: () => {
        const translations = getLocales();
        const language = getLanguage();
        return translations[language][pluginId] || {};
      },

      /**
       * Retrieves the current language.
       *
       * @return {string} The current language.
       */
      getCurrentLanguage: () => {
        return getLanguage();
      },
    });
  };
