const fs = require("fs");
const crypto = require("crypto");
import { uploadImage } from "../modules/client/api";

/**
 * 文件上传
 * @param {String} filePath 文件路径
 * @param {Object} options 上传配置信息
 */
function toUploadImg(filePath, options) {
  const formData = new FormData();

  const buffer = fs.readFileSync(filePath);
  let fsHash = crypto.createHash("md5");
  fsHash.update(buffer);
  formData.append("md5", fsHash.digest("hex"));

  const file = new File([buffer], options.fileName + ".jpg");
  formData.append("file", file);

  Object.entries(options).map(([key, value]) => {
    formData.append(key, value);
  });

  return uploadImage(formData);
}

/**
 * 获取文件的MD5
 * @param {String} source 文件路径
 */
// function getMD5(source) {
//   const buffer = fs.readFileSync(source);
//   let fsHash = crypto.createHash("md5");
//   fsHash.update(buffer);
//   return fsHash.digest("hex");
// }

class UploadTask {
  constructor({ taskList, uploadSuccessCallback, uploadTaskOverCallback }) {
    this.taskList = taskList;
    this.setT = "";
    this.taskRunning = false;
    this.uploadSuccessCallback = uploadSuccessCallback;
    this.uploadTaskOverCallback = uploadTaskOverCallback;

    this.startUploadTask();
  }

  addUploadTask(data) {
    this.taskList.push(data);
  }

  getCurTask() {
    return this.taskList.shift();
  }

  async startUploadTask() {
    if (!this.taskList.length) {
      this.stopUploadTask();
      return;
    }
    this.taskRunning = true;
    const curTask = this.getCurTask();
    const uploadFilePath = curTask.url;

    let uploadResult = "";
    if (uploadFilePath) {
      uploadResult = await toUploadImg(uploadFilePath, curTask).catch(() => {});
      // 失败一次之后，只再重复传一次
      if (!uploadResult)
        uploadResult = await toUploadImg(
          uploadFilePath,
          curTask
        ).catch(() => {});
    }

    if (uploadResult) {
      this.uploadSuccessCallback(curTask);
    }

    this.setT = setTimeout(() => {
      this.startUploadTask();
    }, 200);
  }

  stopUploadTask() {
    this.taskRunning = false;
    if (this.setT) clearTimeout(this.setT);
    this.uploadTaskOverCallback && this.uploadTaskOverCallback();
  }
}

export default UploadTask;
