/**
 * Returns array with any matched <x:[tagNames]> ... <x:[tagNames]> in the translation
 */
export function matchXTags(translation, tagNames) {
  if (!translation || !tagNames || tagNames.length === 0) {
    return [];
  }

  // Future note: string is not regex escaped because tagNames should never have the characters that need to be escaped
  let regex = new RegExp(`<((${tagNames.join(')|(')}))\\b[^>]*>(.*?)<\/\\1>`, "gi");
  let result = translation.match(regex);
  if (result === null) {
    return [];
  }

  return result;
}

function escapeRegExp(str) {
  // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

export function isXTag(variableName) {
  return variableName && variableName.match(/^x:/i);
}

export function generateFragments(translation, parts) {
  if (!translation) {
    return [];
  }

  if (parts.length === 0) {
    return [translation];
  }

  parts = parts.map((part) => {
    return escapeRegExp(part);
  });

  let regex = new RegExp(`(${parts.join('|')})`);
  return translation.split(regex).filter((elem) => {
    return elem.length > 0;
  });
}
