/**
 * 打印操作相关函数
 */
const os = require('os');
const fs = require("fs");
const path = require("path");
const fetch = require("node-fetch");
const pdf_printer = require(".."+path.sep+"module"+path.sep+"pdf-to-printer");
const log = require("."+path.sep+"set_log").clog;

let printOperation={
  //获取打印机列表
  getPrinterList:function(){
    return pdf_printer.getPrinters();
  },
  //获取默认打印机
  getDefaultPrinter:function(){
    return pdf_printer.getDefaultPrinter();
  },
  //打印...
  printing:function (pdfUrl, printer_name,win){
    fetch(pdfUrl)
        .then(res => res.buffer())
        .then(buffer => {
          const pdfPath = this.saveTemporaryFolder(buffer);
          log.info("pdf下载完毕, 准备开始打印, 路径:【"+pdfPath+"】")

          //获取打印缓存
          print_url = os.homedir()+path.sep+"AppData/Local/justarData/print/"
          log.info("打印机缓存目录:"+print_url);
          if(!fs.existsSync(print_url)){
            fs.mkdirSync(print_url);
          }
          fs.writeFileSync(print_url+path.sep+"print.json", JSON.stringify({}), function (err) {
          });
          let thisItem = {};
          thisItem.printer_name = printer_name;
          let jsonstr = JSON.stringify(thisItem);
          fs.writeFileSync(print_url+path.sep+"print.json", jsonstr, function (err) {
            log.error("存入打印机失败:" + err);
          });
          pdf_printer
              .print(pdfPath, {"printer":printer_name})
              .then(this.onSuccess(win))
              .catch(this.onError())
              .finally(() => this.removePdf(pdfPath));
        });
  },
  //保存pdf到临时文件夹
  saveTemporaryFolder:function(buffer){
    const pdfPath = path.join(os.tmpdir(), this.getRandomName() + ".pdf");
    fs.writeFileSync(pdfPath, buffer, "binary");
    return pdfPath;
  },
  //删除内暂存的pdf
  removePdf:function(pdfPath){
    fs.unlinkSync(pdfPath);
  },
  //生成随机pdf名称
  getRandomName:function(){
    return Math.random().toString(36).substring(2);
  },
  //成功回调
  onSuccess:function (win){
    win.close();
    log.info("print success!");
  },
  //失败回调
  onError:function(){
    log.error(error)
  }

}
module.exports = printOperation;
