import { getInputDir, getOutputDir, makeDirSync } from "./env";
const fs = require("fs");
const path = require("path");

/**
 * 旋转图片，并保存为正式文件
 * @param {*} scaningImageList 图片路径
 * @param {String} paperInfo 保持文件名称
 */
export function saveOutputImage(scaningImageList, paperInfo) {
  console.log(scaningImageList);
  let outputOriginPaths = [];
  for (let i = 0; i < scaningImageList.length; i++) {
    const imagePath = scaningImageList[i];
    const originImageFile = saveOriginImage(imagePath, paperInfo);
    outputOriginPaths.push(originImageFile);
    fs.unlinkSync(imagePath);
  }

  return outputOriginPaths;
}

function saveOriginImage(imagePath, paperInfo) {
  console.log(imagePath);
  const outputDir = path.join(getOutputDir("origin"), paperInfo.taskId + "");

  if (!fs.existsSync(outputDir)) makeDirSync(outputDir);
  const outputOriginPath = path.join(outputDir, path.basename(imagePath));
  fs.copyFileSync(imagePath, outputOriginPath);
  return outputOriginPath;
}

/**
 * 获取最早添加的文件
 * @param {String} dir 图片目录
 */
export function getEarliestFile(dir) {
  const ddir = dir || getInputDir();
  const files = fs
    .readdirSync(ddir)
    .filter(fileName => fileName.toLowerCase().match(/\.(jpg|png|jpeg)/))
    .map(fileName => {
      return {
        name: fileName,
        time: fs.statSync(path.join(ddir, fileName)).birthtimeMs
      };
    })
    .sort((a, b) => a.time - b.time);

  if (!files.length) return { url: "", name: "" };

  return {
    url: path.join(ddir, files[0].name),
    name: files[0].name
  };
}

export function getPreUploadFilesAutoSerial(dir) {
  const ddir = dir || getInputDir();
  const files = fs
    .readdirSync(ddir)
    .filter(fileName => fileName.toLowerCase().match(/\.(jpg|png|jpeg)/));

  let imageList = [];
  const len = Math.ceil(files.length / 2);
  for (let i = 0; i < len; i++) {
    const frontFile = path.join(dir, files[2 * i]);
    const versoFile = path.join(dir, files[2 * i + 1]);
    imageList.push({
      frontFile,
      versoFile
    });
  }
  return imageList;
}

export function getPreUploadFileCount(dir) {
  const ddir = dir || getInputDir();
  const files = fs
    .readdirSync(ddir)
    .filter(fileName => fileName.toLowerCase().match(/\.(jpg|png|jpeg)/));

  return Math.ceil(files.length / 2);
}

export function clearDir(dir) {
  fs.readdirSync(dir).forEach(file => {
    fs.unlinkSync(path.join(dir, file));
  });
}

export function getPreUploadFiles(dir) {
  const ddir = dir || getInputDir();
  const files = fs
    .readdirSync(ddir)
    .filter(fileName => fileName.toLowerCase().match(/\.(json)/));

  let imageList = [];
  if (!files.length) return { succeed: false, errorMsg: "当前无扫描文件！" };

  const fileCont = fs.readFileSync(path.join(ddir, files[0]));
  const fileInfo = JSON.parse(fileCont);

  if (!fileInfo.succeed) {
    return { succeed: false, errorMsg: fileInfo.errorMsg };
  }

  imageList = fileInfo.images.map(item => {
    return {
      frontFile: item.front,
      versoFile: item.back
    };
  });
  if (!imageList.length)
    return { succeed: false, errorMsg: "当前无扫描文件！" };

  return { succeed: true, data: imageList };
}

export function renamePreUploadJsonFile(dir) {
  const ddir = dir || getInputDir();
  const files = fs
    .readdirSync(ddir)
    .filter(fileName => fileName.toLowerCase().match(/\.(json)/));
  if (!files.length) return;

  files.forEach(file => {
    fs.renameSync(
      path.join(ddir, file),
      path.join(ddir, path.basename(file, ".json") + ".txt")
    );
  });
}

/**
扫描仪返回的数据
{
	"images": [
		{
			"duplex": true,
			"front": "D:/workspace/project/scan-library/test/00000001_F.jpg",
			"back":"D:/workspace/project/scan-library/test/00000001_B.jpg"
		},
		{
			"duplex": true,
			"front": "D:/workspace/project/scan-library/test/00000001_B.jpg",
			"back":"D:/workspace/project/scan-library/test/00000001_B.jpg"
		}
	],
	"succeed": true,
	"errorMsg":"请将试卷放置到扫描仪上，再进行扫描！"
}
 */
