import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'

export function getCanvas (selector, callback, { width, height }) {
  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]
  })
  const length = items.length
  items.forEach((item) => {
    getCanvas(item, (img, selector) => {
      doc.addImage(img, 'jpeg', 0, 0, mWidth, mHeight)
      if (items[length - 1] === selector) {
        doc.save(`printer-${new Date().getTime()}`)
      } else {
        doc.addPage()
      }
    }, {
      width,
      height
    })
  })
}
