import React, {useState} from 'react';
import {CounterCharacter} from './counter_character';
import {useInterval} from './use_interval';

function convertNumberToArrayOfString(number) {
  let characterArray = parseInt(number).toString().split("");
  while (characterArray.length < 6) {
    characterArray.unshift('0');
  }
  return characterArray;
}

function createCharacterStates(amount, state) {
  let characterArray = convertNumberToArrayOfString(amount);
  let characterStates = [];
  let foundNonZero = false;
  for (const character of characterArray) {
    let leadingZero = true;
    if (!foundNonZero && character != '0') {
      foundNonZero = true;
    }
    if (foundNonZero) {
      leadingZero = false;
    }
    characterStates.push({
      character: character,
      state: state,
      leadingZero: leadingZero,
    });
  }
  return characterStates;
}

export function Counter(props) {
  const {amount, label, cssClass} = props;
  const [counterState, setCounterState] = useState('flashing');
  const [characterStates, setCharacterStates] = useState(() => createCharacterStates(0, 'flashing'));
  const [resolvedCharacterCount, setResolvedCharacterCount] = useState(0);

  if (counterState == 'flashing' && amount != 0) {
    setCounterState('resolving');
    setCharacterStates(createCharacterStates(amount, 'resolving'));
  }

  let delay = null;
  if (counterState == 'resolving') {
    delay = 500;
  }

  useInterval(() => {
    if (resolvedCharacterCount == characterStates.length) {
      setCounterState('resolved');
      return;
    }
    const index = characterStates.length - resolvedCharacterCount - 1;
    const newCharacterStates = [...characterStates];
    newCharacterStates[index].state = 'resolved';
    setCharacterStates(newCharacterStates);
    setResolvedCharacterCount(resolvedCharacterCount + 1);
  }, delay);

  const renderCharacter = (character, index) => {
    return (
      <CounterCharacter
        key={index}
        character={character.character}
        leadingZero={character.leadingZero}
        state={character.state}
      />
    );
  }

  const labelHtml = {__html: label};

  return (
    <div className={cssClass}>
      <div className="characters">
        {characterStates.map((character, index) => renderCharacter(character, index))}
      </div>
      <div className="label" dangerouslySetInnerHTML={labelHtml}></div>
    </div>
  );
}
