// web-worker
self.importScripts('spark-md5.min.js')

self.onmessage = async e => {
  const { chunks } = e.data
  calculate(chunks)
}

async function calculate (chunks) {
  const spark = new self.SparkMD5.ArrayBuffer()
  const total = chunks.length
  const appendToSpark = blob => blob.arrayBuffer().then(arrayBuffer => spark.append(arrayBuffer))
  self.postMessage({ index: 0, total })
  for (let i = 0; i < total; i++) {
    await appendToSpark(chunks[i].raw)
    self.postMessage({ index: i, total })
  }
  self.postMessage({ hash: spark.end() })
}
