import {
  getTmpImgPath,
  getInImgPath,
  getOutImgPath,
  getToolPath,
  getImgDecodeTool
} from "./env";
import { randomCode } from "./utils";
const fs = require("fs");
const path = require("path");
const childProcess = require("child_process");
const gm = require("gm").subClass({
  imageMagick: true,
  appPath: getToolPath("imagemagick")
});

/**
 *  解析图片code信息
 * @param {String} imgPath 图片路径
 * @param {Object} codeArea code所在文件区域信息
 */
function decodeImageCode(imgPath, codeArea) {
  const tmpFile = path.join(getTmpImgPath(), randomCode() + ".jpg");
  const imgObj = gm(imgPath);

  // 裁剪条形码区域
  imgObj.crop(codeArea.width, codeArea.height, codeArea.x, codeArea.y);
  // 旋转
  const rotate = parseInt(codeArea.codeRotate);
  if (rotate) imgObj.rotate("#FFFFFF", rotate);

  return new Promise((resolve, reject) => {
    // 写入临时文件
    imgObj.write(tmpFile, function(err) {
      if (err) {
        reject("error:crop barcode area wrong");
        return;
      }
      // 获取条形码解析工具
      const exec = getImgDecodeTool();
      if (!exec) {
        reject("error:invalid decoder config, should be zxing or zbar");
        return;
      }

      // 解析条形码
      let code;
      try {
        const DecodeResult = childProcess.execSync(`${exec} ${tmpFile}`);
        const codes = DecodeResult.toString()
          .replace(/\r/, "")
          .replace(/\n/, "")
          .split(":");
        if (codes.length <= 2) {
          code = codes[codes.length - 1].replace(/\s+/g, "");
        }
      } catch (e) {
        reject("error:decode exception");
        return;
      }

      fs.unlink(tmpFile, () => {});

      resolve(code);
    });
  });
}

/**
 * 旋转图片，并保存为正式文件
 * @param {*} imgPath 图片路径
 * @param {String} fileName 保持文件名称
 * @param {Object} tailorArea 裁剪区域
 * @param {Number} rotate 旋转角度
 */
function saveFormalImage(imgPath, fileName, tailorArea, rotate) {
  // TODO:根据图片生成对应的后缀路径
  const outputFile = path.join(getOutImgPath(), fileName + ".jpg");
  const imgObj = gm(imgPath);

  // 边缘裁切
  imgObj.crop(tailorArea.width, tailorArea.height, tailorArea.x, tailorArea.y);

  // 旋转
  if (rotate) imgObj.rotate("#FFFFFF", rotate);

  return new Promise((resolve, reject) => {
    imgObj.write(outputFile, function(err) {
      if (err) {
        reject("error: write file wrong");
      }
      resolve(outputFile);
    });
  });
}

/**
 * 获取最早添加的文件
 * @param {String} dir 图片目录
 */
function getEarliestFile(dir) {
  const ddir = dir || getInImgPath();
  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 { decodeImageCode, saveFormalImage, getEarliestFile };
