import path from 'path'
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
  return new Promise((resolve) => {
    if (condition.includes(document.readyState)) {
      resolve(true)
    } else {
      document.addEventListener('readystatechange', () => {
        if (condition.includes(document.readyState)) {
          resolve(true)
        }
      })
    }
  })
}

const fontWeights: [number, string][] = [
  [400, 'Normal'],
  [500, 'Medium'],
  [600, 'Medium'],
  [700, 'Bold'],
  [800, 'Heavy'],
  [900, 'Heavy'],
]

const fontHanSanAbsolute = (weight: string) =>
  `file://${path.resolve(__dirname, `fonts/SourceHanSansCN-${weight}.otf`)}`

function prefetchFontLink(fontPath: string) {
  const link = document.createElement('link')
  link.rel = 'prefetch'
  link.href = fontPath
  link.as = 'font'
  link.type = 'font/otf'
  link.crossOrigin = 'crossOrigin'
  return link
}

function setFontFace(fontFamily: string, weight: number, fontPath: string) {
  return `
    @font-face {
      font-family: ${fontFamily};
      src: url(${fontPath});
      font-weight: ${weight};
    }
  `
}

function provideHanSansFont() {
  const prefetchFragment = document.createDocumentFragment()
  const style = document.createElement('style')
  let styleContent = ''
  fontWeights.forEach(([weight, type]) => {
    const fontPath = fontHanSanAbsolute(type).replace(/\\/g, '/')
    prefetchFragment.append(prefetchFontLink(fontPath))
    styleContent += setFontFace('HanSan', weight, fontPath)
  })
  style.innerHTML = styleContent
  document.head.insertBefore(prefetchFragment, null)
  document.head.appendChild(style)
}

function provideDouYuFont() {
  const fontDouYuAbsolute = `file://${path.resolve(__dirname, `fonts/DOUYU-Font.woff2`)}`.replace(/\\/g, '/')
  const prefetchLink = prefetchFontLink(fontDouYuAbsolute)
  const style = document.createElement('style')
  style.innerHTML = setFontFace('DouYu', 700, fontDouYuAbsolute)
  document.head.insertBefore(prefetchLink, null)
  document.head.appendChild(style)
}

domReady().then(() => {
  /** provideFont */
  provideHanSansFont()
  provideDouYuFont()
})
