let lastSrc // 上次获取的script地址
const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm

/**
 * 获取页面中的script
 *
 */

async function extractNewScripts (url) {
  const html = await fetch('/?_timestamp' + Date.now()).then((resp) => resp.text())
  scriptReg.lastIndex = 0
  const scripts = []
  let match
  while ((match = scriptReg.exec(html))) {
    scripts.push(match.groups.src)
  }
  return scripts
}

/**
 * 检测是否需要更新
 */
async function needUpdate () {
  const scripts = await extractNewScripts()
  if (!lastSrc) {
    lastSrc = scripts
    return false
  }
  let result = false
  if (lastSrc.length !== scripts.length) {
    result = true
  }
  for (let i = 0; i < lastSrc.length; i++) {
    if (scripts[i] !== lastSrc[i]) {
      result = true
      break
    }
  }
  lastSrc = scripts
  return result
}

const DURATION = 3000

export default function autoRefresh () {
  setTimeout(async () => {
    const willUpdate = await needUpdate()
    if (willUpdate) {
      const result = confirm('检测到有版本更新，是否刷新页面？')
      if (result) {
        location.reload()
      }
    }
    autoRefresh()
  }, DURATION)
}
