function checkFont(name) {
  if (!document.fonts) return false;
  const fonts = [...document.fonts.values()];
  return !!fonts.find(font => font.family === name);
}

function loadFont(font) {
  return new Promise(resolve => {
    if (!font) return resolve(true);
    const { name, url, descriptors = {} } = font;
    if (!name || !url) return resolve(true);
    if (!document.fonts || checkFont(name)) return resolve(true);
    const fontFace = new FontFace(name, `url(${url})`, descriptors);
    fontFace
      .load()
      .then(font => {
        document.fonts.add(font);
        resolve(true);
      })
      .catch(err => {
        console.error(err);
        resolve(true);
      });
  });
}

function allSettled(arr) {
  return new Promise(resolve => {
    let res = [];
    const push = data => {
      res.push(data);
      if (res.length === arr.length) {
        resolve(res);
      }
    };
    arr.forEach(p => {
      p.then(value => {
        push({ status: 'fulfilled', value });
      }).catch(reason => {
        push({ status: 'rejected', reason });
      });
    });
  });
}

export default async function (fonts) {
  if (typeof fonts === 'string' && fonts.length > 0) {
    fonts = fonts.split('|').map(font => {
      font = font.split('=');
      const [name, url] = font;
      return { name, url };
    });
  }
  if (!Array.isArray(fonts) && !fonts.length) return;
  console.log('fonts', fonts);
  return allSettled(fonts.map(font => loadFont(font)));
}
