//  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.
function transformSpecialChar(str: string) {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

export function loadXML(xmlString: string) {
  const titleReg = /<title>\s*([\s\S]*?)\s*<\/title>/;
  const titleSNReg = /<title>[\s\S]*?SN\s*:\s*(\S*)\s*[\s\S]*<\/title>/;
  const paramReg = /<param[\s\S]*?\/>/g;
  const obj = {
    title: '',
    SN: '',
  };
  if (titleReg.test(xmlString) && RegExp.$1) {
    obj.title = RegExp.$1;
  }
  if (titleSNReg.test(xmlString) && RegExp.$1) {
    obj.SN = transformSpecialChar(RegExp.$1);
  }
  const paramArr = xmlString.match(paramReg);
  if (paramArr?.length) {
    const paramNameReg = /[\s\S]*name\s*=\s*"(\S*)\s*"[\s\S]*\/>/;
    const paramValueReg = /[\s\S]*value\s*=\s*"([\S\s]*)"[\s\S]*\/>/;
    let key: any;
    let value: any;
    paramArr.forEach(param => {
      if (paramNameReg.test(param)) {
        key = RegExp.$1;
      }
      if (paramValueReg.test(param)) {
        value = RegExp.$1;
      }
      if (key && !obj[key] && value) {
        if (key === 'vmm_compress' || key === 'compress') {
          value = parseInt(value, 10);
        }
        obj[key] = value;
      }
    });
  }
  return obj;
}

export function stringToBytes1(str: string) {
  if (typeof str !== 'string') {
    return str;
  }
  let ch;
  const st8 = [0x08];
  const st16 = [0x10];
  let isUtf16 = 0;
  for (let i = 0; i < str.length; i++) {
    ch = str.charCodeAt(i);
    if (ch > 0x00 && ch < 0x80) {
      st8.push(ch & 0xff);
      st16.push(0x00);
      st16.push(ch & 0xff);
    } else {
      st16.push((ch >> 8) & 0xff);
      st16.push(ch & 0xff);
      isUtf16 = 1;
    }
  }
  return isUtf16 === 1 ? st16 : st8;
}
