import * as React from 'react';
import styles from './index.less';
import { IRenderer } from '../../index.data';
import { NumericFormat } from '../../../index.data';

const NumericRenderer: IRenderer<number> = ({ id, value = 0, style, format, getRow }) => {
  return (
    <div className={styles['container']} style={style}>
      {getFormattedValue(value, format)}
    </div>
  );
};

export default NumericRenderer;

export function getFormattedValue(value: any, format: NumericFormat | undefined) {
  const {
    decimalLength = 0,
    scale = 1.0,
    zeroValue = false,
    percent = false,
    showThousandsSeparator,
  } = format || ({} as any);
  const x =
    zeroValue && value === 0
      ? ''
      : percent
      ? (scale * value * 100.0).toFixed(decimalLength) + '%'
      : (scale * value).toFixed(decimalLength);

  return x && showThousandsSeparator ? setThousandsSeparator(x) : x;
}

export function setThousandsSeparator(x: string) {
  const _pointIndex = x.indexOf('.');
  const pointIndex = _pointIndex < 0 ? x.length : _pointIndex;
  // 111.1 => 111.1, 此时i=3
  // 111 => 111, 同样i=3, 因为111=>111.0
  if (pointIndex <= 3) return x;

  const leading = x.substring(0, pointIndex);
  let leadingFormated = '';

  // for performance
  for (let i = 0; i < pointIndex; i++) {
    // 1234567.1 => 1,234,567.1, 注意,号加在 i_invert=2|5后
    // pointIndex = 7, i=0, 此时 i_invert = 6
    // pointIndex = 7, i=6, 此时 i_invert = 0
    const i_invert = pointIndex - i - 1;
    leadingFormated = leading[i_invert] + leadingFormated;
    if ((i + 1) % 3 === 0) {
      leadingFormated = ',' + leadingFormated;
    }
  }
  return stripLeadingFlag(
    _pointIndex < 0 ? leadingFormated : leadingFormated + x.substring(pointIndex),
  );
}

function stripLeadingFlag(s: string) {
  return s.startsWith(',') ? s.substring(1) : s.startsWith('-,') ? '-' + s.substring(2) : s;
}
