// Copyright (c) Huawei Technologies Co., Ltd. 2022-2024. All rights reserved.
// 
// this file licensed under the 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.
export const firstNonEmpty = (...vals: any[]): any => {
  for (const v of vals) {
    if (v !== undefined && v !== null && v !== '') {
      return v;
    }
  }
  return '';
};

export const fmt = (v: any, unit?: string): string => {
  if (v === undefined || v === null || v === '') {
    return '';
  }
  const s = Array.isArray(v) ? v.join('/') : String(v);
  return unit ? `${s} ${unit}` : s;
};

export const fmtCoreThread = (
  cores: any,
  threads: any,
  coresLabel = 'cores',
  threadsLabel = 'threads'
): string => {
  const c = firstNonEmpty(cores, '');
  const th = firstNonEmpty(threads, '');
  if (c !== '' && th !== '') {
    return `${c} ${coresLabel}/${th} ${threadsLabel}`;
  }
  return firstNonEmpty(c, th, '');
};

export const fmtCacheTriple = (
  l1: any,
  l2: any,
  l3: any,
  unit = 'KB'
): string => {
  const a = [l1, l2, l3].map((v) =>
    v === undefined || v === null || v === '' ? '' : String(v)
  );
  if (a.every((s) => s === '')) {
    return '';
  }
  const joined = a.map((s) => s || '0').join('/');
  return `${joined} ${unit}`;
};

export const formatBytesIEC = (bytes: any): string => {
  const n = Number(bytes);
  if (!Number.isFinite(n) || n <= 0) {
    return '';
  }
  const TB = 1024 ** 4;
  const GB = 1024 ** 3;
  return n >= TB
    ? `${(n / TB).toFixed(2)} TB`
    : `${(n / GB).toFixed(2)} GB`;
};

export const normalizeBySuffixNumber = (
  name?: string,
  prefix = ''
): string => {
  if (!name) {
    return '';
  }
  const raw = String(name).toUpperCase().replace(/[\s_-]/g, '');
  const m = raw.match(/(?<suffixNumber>\d+)$/);
  return m ? `${prefix}${m[1]}` : raw;
};
