import getSymbolsInPatternWithPosition from '../getSymbolsInPatternWithPosition';
import type { SymbolWithPosition } from '../getSymbolsInPatternWithPosition/getSymbolsInPatternWithPosition';

const formatWithPattern = (value: string, pattern: string): string => {
  if (!value || value === '') {
    return '';
  }

  const valueArray = value.toString().split('');

  const patternWithSymbolsPosition = getSymbolsInPatternWithPosition(pattern);

  let patternSymbol: SymbolWithPosition[] = [];
  // valueArray.length increments during the cycle cause we are adding new elements.
  for (let index = 0; index < valueArray.length; index += 1) {
    patternSymbol = patternWithSymbolsPosition.filter((pattern) => pattern.index === index);
    // Add pattern's symbol at n position
    if (patternSymbol.length === 1) {
      const last = patternSymbol.pop();
      if (last) {
        valueArray.splice(index, 0, last.symbol);
      }
    }
  }

  return valueArray.join('');
};

export default formatWithPattern;
