import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import SntQueue from '@/plugins/queue'

export function getCanvas (selector, callback, { width, height }) {
  return html2canvas(document.getElementById(selector), {
    width,
    height
  }).then((canvas) => {
    callback(canvas.toDataURL('image/jpeg'), selector)
  })
}

export function savePdf (items, { width, height }) {
  const mm = 0.2645833333
  const mWidth = width * mm
  const mHeight = height * mm
  const doc = jsPDF({
    unit: 'mm',
    format: [mWidth, mHeight]
  })
  SntQueue.beginTransition()
  SntQueue.forEach(items, (item, index) => {
    getCanvas(item, (img) => {
      doc.addImage(img, 'jpeg', 0, 0, mWidth, mHeight)
      if (index !== items.length - 1) doc.addPage()
    }, {
      width,
      height
    })
  })
  const result = new Promise((resolve) => {
    SntQueue.add(() => {
      doc.save(`printer-${new Date().getTime()}`)
      resolve()
    })
  })
  SntQueue.endTransition()
  return result
}
