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

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

function readChunk (file, chunkSize, offset) {
  return file.slice(offset, offset + chunkSize).arrayBuffer().then(arrayBuffer => new Uint8Array(arrayBuffer))
}

async function calculate (obj) {
  self.MediaInfo().then(mediaInfo => {
    const { totalSize, file } = obj
    mediaInfo
      .analyzeData(() => totalSize, (...args) => readChunk(file, ...args))
      .then(result => {
        self.postMessage({ media: result.media })
      })
      .catch(e => {
        self.postMessage({ error: e })
      })
  }, e => {
    self.postMessage({ error: e })
  })
}
