//  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 { langOptions } from './language';
import { getLocationSearch, urlStandardization } from './utils';

function setKvmSearch() {
  /**
   * 检测是不是KVM连接
   * KVM连接分2种
   * 1. KVM直连1，这种方式是用户通过在浏览器地址栏的URL后面添加remoteconsole或kvmvmm.asp或login.html?redirect_type=1
   *    来实现期望跳转至KVM页面（实际还在登录页，登录后直接跳转到KVM页面，不会跳转到Home，称为URL直连）
   *    login.html+kvmvmm.asp是java模式，remoteconsole下明确指定了openWay=java/jre/或者不写参数时为java，
   *    明确指定了openway=html时为html5方式，其他无效的值不做处理
   * 2. KVM直连2，用户通过拼接URL地址的形式，将session信息等放在浏览器地址栏的URL参数栏中
   *    此时，KVM会话已经建立，直接跳转到KVM页面，不需要跳转到登录页(称为Key直连)
   * 3. kvmHtml5Info这个字段是通过URL拼接的形式，访问UI/Rest/KVMHandle接口，后端存储的字段
   */
  const kvmMark = ['remoteconsole', 'kvmvmm.asp'];
  const redirectType = 'login.html?redirect_type=1';
  const search = self.location.search;
  const _path = self.location.pathname.substring(1);
  const isAspWay = kvmMark[1].includes(_path);
  const isRemoteWay = kvmMark[0].includes(_path);
  const isRedirectWay = redirectType === `${_path}${search}`;

  // 是KVM直连方式时，先写入kvmConnect和kvmSearch，然后在判断是html5还是java形式的直连方式
  if (_path.length > 0 && (isAspWay || isRemoteWay || isRedirectWay)) {
    self.sessionStorage.setItem('kvmConnect', '1');
    if (search) {
      self.sessionStorage.setItem('kvmSearch', search);
    }

    let type = '';
    if (isAspWay || isRedirectWay) {
      type = 'java';
    }

    /**
     * 只有明确标注了openWay等于java/jre或者"不带openWay"的情况下，才是java模式。
     * 若带了openWay，又不标注值，则不做处理（会清空账号密码）
     * openWay中的W不区分大小写，但是整体单词是区分大小写的
     */
    if (isRemoteWay) {
      const _search = getLocationSearch(search) as any;
      const openWay = _search.openWay !== undefined ? _search.openWay : _search.openway;
      if (openWay === 'html5') {
        type = 'html5';
      }

      if (openWay === undefined || openWay === 'java' || openWay === 'jre') {
        // 注意：如果openWay整体单词大小写不分，则这里是按 undefined处理的，因此是java方式
        type = 'java';
      }
    }

    // 为java模式时，增加kvmJava字段，为非java模式时删除kvmJava字段
    if (type === 'java') {
      self.localStorage.setItem('kvmJava', '1');
    } else {
      self.localStorage.removeItem('kvmJava');
    }
  }
}

function setKvmLanguage() {
  // SSO直连方式（KVM或首页都包括）
  let lang = '';
  const localKvmH5Info = JSON.parse(localStorage.getItem('kvmHtml5Info') as string);
  const sessionKvmH5Info = JSON.parse(sessionStorage.getItem('kvmHtml5Info') as string);
  const ssoLoginInfo = JSON.parse(localStorage.getItem('ssoLoginInfo') as string);
  const params: any = getLocationSearch(self.location.search);
  /**
   * 1. 使用SSO跳转KVM时带的语言
   * 2. 使用URL直连方式带的语言
   */
  if (localKvmH5Info || sessionKvmH5Info) {
    let kvmLang = '';
    if (localKvmH5Info) {
      kvmLang = localKvmH5Info.lp || localKvmH5Info.lang;
    } else {
      kvmLang = sessionKvmH5Info.lp || sessionKvmH5Info.lang;
    }
    if (kvmLang === 'cn') {
      kvmLang = 'zh';
    }
    lang = kvmLang;
  } else if (Object.keys(params).length > 0) {
    let paramLang = params.lp || params.lang;
    let lp = paramLang ? paramLang.toLowerCase() : '';
    lang = lp === 'cn' ? 'zh' : lp;
  } else if (ssoLoginInfo) {
    const ssoLocale = self.localStorage.getItem('locale');
    if (ssoLocale) {
      lang = transformSSOLang(ssoLocale.toLowerCase());
      self.localStorage.removeItem('locale');
    }
  }
  if (lang) {
    localStorage.setItem('kvmLocale', lang);
  }
}

// 转换SSO跳转时的语言, SSO跳转传递过来的是 zh-CN, en-US, ja-JA, fr-FR,ru-RU
function transformSSOLang(ssoLang: string) {
  let lang = '';
  const supportsLang = langOptions.map(item => item.id);
  supportsLang.forEach(item => {
    if (ssoLang.indexOf(item) > -1) {
      lang = item;
    }
  });
  return lang;
}

export function kvmParamInit() {
  setKvmSearch();
  setKvmLanguage();
  urlStandardization();
}
