const DOM_PARSER = new DOMParser();
const TEXTAREA = document.createElement('textarea');

export function stringToRGB(str) {
  let i;
  let hash = 0;
  if (str.length === 0) {
    return hash;
  }
  for (i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
    hash = hash & hash;
  }
  const rgb = [0, 0, 0];
  for (i = 0; i < 3; i++) {
    const value = (hash >> (i * 8)) & 255;
    rgb[i] = value;
  }
  return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
}

export function htmlToText(htmlContent) {
  if (!htmlContent) {
    return '';
  }
  let content;
  try {
    content = DOM_PARSER.parseFromString(htmlContent, 'text/html').documentElement.innerText.trim();
  } catch (e) {
    content = htmlContent.replace(/<[^>]+>/g, '').trim();
  }
  TEXTAREA.innerHTML = content;
  content = TEXTAREA.value;
  return content.replace(/[\r|\n|\t]/g, ' ').replace(/ +(?= )/g,' ');
}