const fs = require("fs");
const crypto = require("crypto");
import {
  uploadSliceImage,
  uploadFormalImage,
  uploadStudent,
  saveCollectLog
} from "../modules/client/api";

/**
 * 文件上传
 * @param {Object} options 上传配置信息
 * @param {String} type 上传类型：formal=>原图，slice=>剪切图
 */
function toUploadImg(options, type) {
  const formData = new FormData();
  const filePath =
    type === "formal" ? options.formalImgPath : options.sliceImgPath;

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

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

  return type === "formal"
    ? uploadFormalImage(options, formData, { headers: { md5 } })
    : uploadSliceImage(options, formData, { headers: { md5 } });
}

function toUploadStudent(options) {
  const datas = {
    subjectId: options.subjectId,
    examNumber: options.examNumber,
    absent: false,
    manual: options.isManual
  };
  return uploadStudent(datas);
}

/**
 * 获取文件的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() {
    this.taskRunning = true;
    this.runUploadTask();
  }

  async runUploadTask() {
    if (!this.taskList.length || !this.taskRunning) {
      this.overUploadTask();
      return;
    }
    const curTask = this.getCurTask();

    const uploadRequest = [
      toUploadImg(curTask, "formal"),
      toUploadImg(curTask, "slice")
    ];
    const uploadResult = await Promise.all(uploadRequest).catch(() => {});

    if (uploadResult) {
      const updateRequest = [toUploadStudent(curTask), saveCollectLog(curTask)];
      const updateResult = await Promise.all(updateRequest).catch(() => {});

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

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

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

export default UploadTask;
