/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
export const toSeconds = (milliseconds: number): number => {
  if (!milliseconds) {
    return 0;
  }

  return milliseconds / 1000;
};

export const toSignificantFigure = (value: number, precision = 3): string => {
  return value.toPrecision(precision);
};

export const formatNumberWithPrecision = (value: number, precision = 1): string => {
  if (!value && value !== 0) {
    return '';
  }

  if (value % 1 !== 0) {
    value = Number(value.toFixed(precision));
  }

  return value.toLocaleString();
};

export const addTrailingZeroToPercentage = (stringNumber: string): string => {
  if (!stringNumber || stringNumber === '%') {
    return '';
  }

  if (stringNumber.indexOf('.') > -1) {
    return stringNumber;
  }

  return stringNumber.replace('%', '.0%');
};

export const formatToLocalString = (value: string | number): string => {
  return Number(value).toLocaleString();
};

export const formatWithUnits = (value: number, valueUnits: string): string => {
  const sizeUnits = [
    {
      value: 1,
      symbol: ''
    },
    {
      value: 1e3,
      symbol: 'k'
    },
    {
      value: 1e6,
      symbol: 'M'
    },
    {
      value: 1e9,
      symbol: 'G'
    },
    {
      value: 1e12,
      symbol: 'T'
    },
    {
      value: 1e15,
      symbol: 'P'
    },
    {
      value: 1e18,
      symbol: 'E'
    }
  ];
  const valueSize =
    sizeUnits
      .slice()
      .reverse()
      .find(unit => {
        return value >= unit.value;
      }) || sizeUnits[0];
  let formatedValue = (value / valueSize.value).toFixed(2) || 0;

  if (valueSize !== sizeUnits[0]) {
    formatedValue = String(formatedValue).substring(0, 3);

    while (formatedValue.replace('.', '').length !== 3) {
      formatedValue += '0';
    }
  }

  return `${formatedValue}${valueSize.symbol}${valueUnits}`;
};
