import { BigNumber } from '@polymathnetwork/polymesh-sdk';
import moment from 'moment';
import { hexToString, isHex, stringToHex } from '@polkadot/util';

export const shortenString = (
  string: string,
  { size = 17 }: { size?: number } = {}
) => {
  const minSize = 5;
  if (size < minSize) {
    throw new Error('Cannot shorten string to less than 5 characters');
  }

  const portionSize = Math.floor((size - 3) / 2);
  const remainder = ((size - 3) / 2) % 1 !== 0 ? 1 : 0;

  if (string.length <= size) return string;

  return `${string.substring(0, portionSize + remainder)}...${string.slice(
    -portionSize
  )}`;
};

export const trimString = (string: string, size = 17) =>
  string.length > size ? `${string.slice(0, size).trim()}...` : string;

export const formatAmount = (amount: BigNumber, minimumFractionDigits = 0) => {
  const formatter = new Intl.NumberFormat('en-US', {
    minimumFractionDigits,
  });
  return formatter.format(parseFloat(amount.toString()));
};

export const formatFileSize = (bytes: number) => {
  let val = bytes;
  let suffix = '';
  if (val < 1000) {
    suffix = 'B';
  } else {
    val /= 1024;
    if (val < 1000) {
      suffix = 'KB';
    } else {
      val /= 1024;
      if (val < 1000) {
        suffix = 'MB';
      } else {
        val /= 1024;
        if (val < 1000) {
          suffix = 'GB';
        } else {
          val /= 1024;
          suffix = 'TB';
        }
      }
    }
  }
  return Math.floor(val * 100) / 100 + suffix;
};

export const toDateString = (date: string | Date, expanded = false) => {
  const dateAsMoment = moment(date);
  return expanded
    ? dateAsMoment.format('DD MMMM, YYYY')
    : dateAsMoment.format('MM/DD/YYYY');
};

export const toDateTimeString = (date: string | Date, expanded = false) => {
  const dateAsMoment = moment(date);
  return expanded
    ? dateAsMoment.format('HH:MMa, D MMMM, YYYY')
    : dateAsMoment.format('MM/DD/YYYY LT');
};

export const splitOnCapitalLetter = (input: string) =>
  input.split(/(?=[A-Z])/).join(' ');

export const stringToUnpadded = (input: string) => input.replace(/\0/g, '');

export const hexToUnpaddedString = (hex: string) =>
  stringToUnpadded(isHex(hex) ? hexToString(hex) : hex);

export const stringToPadded = (string: string, maxChars = 12) =>
  `${string}${'\u0000'.repeat(maxChars - string.length)}`;

export const stringToPaddedHex = (string: string) =>
  stringToHex(stringToPadded(string));

export const formatNumberForChain = (number: number | string) => {
  return Number(number) * 10 ** 6;
};

export const formatNumberFromChain = (number: number | string) => {
  return Number(number) / 10 ** 6;
};
