import Enact_$L from "@enact/i18n/$L";
import stringReSource from "../../resources/strings.json";

export const $L = (str) => {
  let languageSetting = "system";
  let language = "en";

  if (
    typeof window === "object" &&
    window.store &&
    window.store.getState().common &&
    window.store.getState().common.localSettings
  ) {
    languageSetting =
      window.store.getState().common.localSettings.languageSetting;
  }

  if (
    typeof window === "object" &&
    window.PalmSystem &&
    languageSetting === "system"
  ) {
    return Enact_$L(str).replace(/{br}/g, "{br}");
  } else if (typeof window === "object") {
    language =
      typeof window.navigator === "object"
        ? window.navigator.language || window.navigator.userLanguage
        : "en-US";

    if (languageSetting !== "system") {
      language = languageSetting;
    }

    language = language.split("-")[0];

    const resource = stringReSource[language] || stringReSource.en;

    if (typeof str === "object") {
      if (resource && resource[str.key]) {
        return resource[str.key].replace(/{br}/g, "{br}");
      } else {
        return str.value;
      }
    } else if (resource && resource[str]) {
      return resource[str].replace(/{br}/g, "{br}");
    }
  }

  return str && str.replace(/{br}/g, "{br}");
};
