import SparkMD5 from 'spark-md5'

// md5值计算
var fileMd5Sum = (file) => {
    console.log(new Date().toDateString())

    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onloadend = evt => {
            const spark = new SparkMD5.ArrayBuffer();
            spark.append(evt.target.result);
            const md5 = spark.end();
            resolve({ md5, file });
        };
        fileReader.onerror = () => {
            reject({ message: "文件解析失败" });
        }
        fileReader.readAsArrayBuffer(file);
    });
}


const getFileMD5Progress = (file, progress) => {
    return new Promise((resolve, reject) => {
        const chunkSize = 2097152; // 每次读取2MB.
        const chunks = getFileChunk(file, chunkSize);
        const spark = new SparkMD5.ArrayBuffer();
        let currentChunkIndex = 0;
        const loadNext = () => {
            const reader = new FileReader();
            reader.onload = e => {
                progress && progress(Math.round(currentChunkIndex / chunks.length * 100) + "%");
                currentChunkIndex++;
                spark.append(e.target.result);
                if (currentChunkIndex < chunks.length) {
                    loadNext();
                } else {
                    const md5 = spark.end();
                    resolve({ md5, file });
                }
            };
            reader.readAsArrayBuffer(chunks[currentChunkIndex]);
        };
        loadNext();
    });
};

const getFileChunk = (file, chunkSize) => {
    const chunks = [];
    const fileSize = file.size;
    let currentChunkStart = 0;
    while (currentChunkStart < fileSize) {
        const chunkEnd = currentChunkStart + chunkSize;
        const chunk = file.slice(currentChunkStart, chunkEnd);
        chunks.push(chunk);
        currentChunkStart = chunkEnd;
    }
    return chunks;
};

export {
    fileMd5Sum,
    getFileMD5Progress
}
