import FontFaceObserver from 'fontfaceobserver'
import { Promise } from 'es6-promise'

const htmlTag = document.documentElement

function loadProxima() {
  const observer = new FontFaceObserver('Proxima Nova Subset', {
    weight: 400,
  })
  
  observer.load().then(() => {
    htmlTag.className = htmlTag.className.replace('proxima-not-loaded', 'proxima-subset-loaded')

    Promise.all([
      (new FontFaceObserver('Proxima Nova', { weight: 400 })).check(null, 5000),
      (new FontFaceObserver('Proxima Nova', { weight: 700 })).check(null, 5000),
    ]).then(() => {
      htmlTag.className = htmlTag.className.replace(/(?:^|\s)proxima-subset-loaded(?!\S)/, '')
      sessionStorage.proximaLoaded = true
    })
  })
}

export default {
  init: () => {
    const fontsAreLoaded = (
      sessionStorage.proximaLoaded
      && sessionStorage.circularLoaded
    )

    if (fontsAreLoaded) {
      // remove `-not-loaded` classes
      htmlTag.className = htmlTag.className.replace(
        /(?:^|\s)(proxima|circular)-not-loaded(?!\S)/g,
        ''
      )
    } else {
      loadProxima()
    }
  },
}
