import { FontInfo } from 'models/font.types';

export function addFontsByStyle(fonts: FontInfo[]) {
  const heads = document.getElementsByTagName('head');
  const oldFontStyle = document.querySelector('head #fonts');
  const style = document.createElement('style');
  style.setAttribute('type', 'text/css');
  style.setAttribute('id', 'fonts');
  const cssString = fonts.map((d) => `@font-face { font-family: '${d.name}'; src: url('${d.src}');}`);
  const cssText = document.createTextNode(cssString.join('\n'));
  style.appendChild(cssText);
  if (heads.length) {
    if (oldFontStyle) {
      heads[0].removeChild(oldFontStyle);
    }
    heads[0].appendChild(style);
  }
}
