import { typeOf } from 'ember-utils';
import {
  HASHTAG_REGEXES
} from 'web-client/utilities/bits/constants-config';
/* Used to tokenize and render Bits, i.e. for chat messages */

function tokenize(bitsWord, prefix) {
  let integerMatch = bitsWord.match(/\d+/)[0];
  let length = prefix.length + integerMatch.length;
  let amount = parseInt(integerMatch);

  return {
    type: 'bits',
    amount: amount,
    prefix: prefix,
    length: length
  };
}

export function tokenizeBits(tokens, tags = [], regexes) {
  let newTokens = [];
  if (typeOf(tokens) !== 'array') {
    tokens = [tokens];
  }

  let tagSet = false;
  tokens.forEach((token) => {
    if (typeof(token) === 'string') {
      let words = token.split(' ');
      let lastWordIndex = words.length - 1;
      let nextTextToken = '';

      words.forEach((word, index) => {
        let matched = false;
        regexes.forEach((regex) => {
          if (word.match(regex.valid)) {
            matched = true;
            newTokens.push(`${nextTextToken} `, tokenize(word, regex.prefix));
            nextTextToken = '';
            return;
          }});

          if (matched) {
            return;
          }

          if (!tagSet && HASHTAG_REGEXES.VALID.test(word) && tags.includes(word.substring(1))) {
            tagSet = true;
            newTokens.push(`${nextTextToken} `);
            newTokens.push({
              type: 'bits-tag',
              tag: word,
              length: word.length
            });
            nextTextToken = '';
          } else {
            nextTextToken += word;
            if (index < lastWordIndex) {
              nextTextToken += ' ';
            }
          }
      });

      if (nextTextToken) {
        newTokens.push(nextTextToken);
      }
    } else {
      newTokens.push(token);
    }
  });

  return newTokens;
}
