//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { saveStoreToLocal } from './common-service';
import { setStoreData } from './composition';

let i18nInstance: any = null;
const langOptions = [
  { id: 'en', label: 'English', elId: 'en-US' },
  { id: 'zh', label: '简体中文', elId: 'zh-CN' },
  { id: 'ja', label: '日本語', elId: 'ja-JA' },
  { id: 'fr', label: 'Français', elId: 'fr-FR' },
  { id: 'ru', label: 'Русский', elId: 'ru-RU' },
];

/**
 * 语言优先级定义
 * 1. KVM直连或SSO跳转KVM（首页）时指定了语言项，优先级：0
 * 2。上次使用过得语言，优先级：1
 * 3. 当前浏览器的语言，优先级：3
 * 将语种优先级逐步代入到后端支持的语种列表中，若都不支持，则默认显示英文
 */
function computeWebLanguage(langSet: string[] = []): string {
  const kvmLang = localStorage.getItem('kvmLocale');
  const loct = localStorage.getItem('loct');
  const browseLang = computedNavigatorLang();
  if (kvmLang && langSet.includes(kvmLang)) {
    localStorage.removeItem('kvmLocale');
    return kvmLang;
  }

  if (loct) {
    const locale = JSON.parse(loct).locale;
    if (langSet.includes(locale)) {
      return locale;
    }
  }

  if (langSet.includes(browseLang)) {
    return browseLang;
  }

  return 'en';
}

// 计算浏览器语言
function computedNavigatorLang() {
  let lang = 'en';
  const browserLang = navigator.language.toLowerCase();
  const supportsLang = langOptions.map(item => item.id);
  supportsLang.forEach(sLang => {
    if (browserLang.indexOf(sLang) > -1) {
      lang = sLang;
    }
  });
  return lang;
}

// 保存i18n的实例
function saveI18nInstance(instance: any) {
  i18nInstance = instance.global;
}

// 翻译
function traduction(str: string, arg?: any): string {
  if (arg || arg === 0) {
    return i18nInstance?.t(str, arg);
  } else {
    return i18nInstance?.t(str);
  }
}

// 获取错误的翻译
function getErrorTranslate(errorId: string) {
  if (!errorId) {
    return errorId;
  }
  const errorMessage = traduction(`${errorId}.errorMessage`);
  const attrMessage = traduction(`${errorId}.attrMessage`);
  const message = traduction(`${errorId}.message`);

  // 优先使用attrMessage
  if (attrMessage.indexOf(errorId) < 0) {
    return attrMessage;
  }

  if (errorMessage.indexOf(errorId) < 0) {
    return errorMessage;
  }

  if (message.indexOf(errorId) < 0) {
    return message;
  }

  return traduction('COMMON_FAILED');
}
// 通过修改body得class来实现针对特定语言的样式hack
function setExtrasCss(lang: string) {
  (document.querySelector('#app') as HTMLAnchorElement).className = lang;
}

export function setLangData(langSet: any) {
  // 计算使用的语言
  const locale = computeWebLanguage(langSet);
  setStoreData('loct', 'locale', locale);
  saveStoreToLocal();
  setExtrasCss(locale);

  // 计算支持的语言列表
  const langs = langOptions.filter(lang => {
    return langSet.indexOf(lang.id) > -1;
  });

  setStoreData('glob', 'langOptions', langs);
}

export { computeWebLanguage, langOptions, traduction, saveI18nInstance, getErrorTranslate };
