
export const categoryColors = {
  topic: 'black',
  approval: '#00FF7F',
  disapproval: '#ff6666',
  question: '#3399ff',
  reference: '#FFFF66',
  important: '#abd9e9',
  keyword: '#c2a5cf',
  comment: '#abdda4',
  trouble: '#fdae61',
  call: '#007533',
  highlight: '#ffff3c',
};

export const categoryStyles = (cat) => {
  const color = categoryColors[cat];
  if (color) {
    return { backgroundColor: color, fontWeight: 'normal' };
  }
  return {};
};

export function getAnnotationStyle(annotation, metacategories) {
  let style = 'highlight';
  annotation.tags.some((tag) => {
    const tagStr = tag.startsWith('cat:') ? tag.substring(4) : tag;
    const tagStrLc = tagStr.toLowerCase();
    let metacategory = false;
    if (tag.startsWith('cat:')) {
      metacategory = metacategories.find(mc => mc.tag === tagStrLc);
    }
    if (metacategory) {
      style = metacategory.id;
      return true;
    }
    return false;
  });
  return categoryStyles(style);
}

export function isDefinitionInTags(tags) {
  return (
    tags.includes('définition')
    || tags.includes('definition')
    || tags.includes('act:définition')
    || tags.includes('act:definition')
    || tags.includes('act:def')
  );
}

// taken from https://github.com/disqus/disqus-react/blob/master/src/utils.js
export function insertScript(src, id, parentElement, attrs = {}) {
  const script = window.document.createElement('script');
  script.async = true;
  script.src = src;
  script.id = id;
  Object.keys(attrs).forEach((k) => {
    script.setAttribute(k, attrs[k]);
  });
  parentElement.appendChild(script);

  return script;
}

// take from https://github.com/disqus/disqus-react/blob/master/src/utils.js
export function removeScript(id, parentElement) {
  const script = window.document.getElementById(id);
  if (script) {
    parentElement.removeChild(script);
  }
}

export function getTerms(annotations) {
  return annotations.reduce((res, annotation) => {
    const tags = annotation.tags.map(t => t.toLowerCase());

    if (!tags.includes('cat:mot-clef')) {
      return res;
    }

    let term;

    (annotation.target[0].selector || []).some((selector) => {
      if (selector.type === 'TextQuoteSelector' && selector.exact) {
        term = selector.exact.trim().toLowerCase();
        return true;
      }
      return false;
    });

    if (term) {
      res[term] = (res[term] || []);
      res[term].push(annotation);
    }
    return res;
  }, {});
}

export function toBase64(msg) {
  return Buffer.from(msg).toString('base64');
}

export function getTermId(term, dashboardId) {
  return toBase64(dashboardId ? `${dashboardId}::${term}` : term);
}
