import CryptoJS from 'crypto-js/crypto-js'


const bufferChunkSize = 1024 * 1024 * 5;

export const fileHash = (file, config={}) => {
  config = {
    algo: 'MD5',
    enc: 'Hex',
    onProgress: (a,b)=>{console.debug(a,b)}
    ,...config
  }
  return new Promise((resolve, reject) => {
    if(file==null || file.size==0){
      resolve(null)
      return 
    }
    const hash = CryptoJS.algo[config.algo].create()
    let count = 0;
    const reader = new FileReader()

    // 以流的方式读取文件
    function readChunk(start, end) {
      const slice = file.slice(start, end)
      reader.readAsArrayBuffer(slice);
    }

    // 递归读取文件的每个分块
    function processChunk(offset) {
      const start = offset;
      const end = Math.min(start + bufferChunkSize, file.size)
      count = end

      readChunk(start, end)
    }

    // 当读取完整个文件后，计算哈希值并返回
    reader.onloadend = function () {
      const arrayBuffer = reader.result
      const wordArray = CryptoJS.lib.WordArray.create(arrayBuffer)

      // 更新哈希对象
      hash.update(wordArray)
      config.onProgress(count,file.size)
      if (count < file.size) {
        // 继续处理下一个分块
        processChunk(count)
      }
      else {
        // 计算哈希值并返回
        const ret = hash.finalize()
        resolve(ret.toString(CryptoJS.enc.Hex))
      }
    }
    config.onProgress(count,file.size)
    // 开始处理文件内容分块
    processChunk(0)

  })
}