import { promisify } from 'node:util'
import child_process from 'node:child_process'
import { existsSync, mkdirSync } from 'node:fs'
import { writeFile } from 'node:fs/promises'
import { jsPDF } from 'jspdf'

const labelByPrinter = (doc, no, entry) => {
  if(entry.labelPrinterId === 'b') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(18)
    doc.text(String(entry.product.replace("FOREVER ", "")), 0, 8)
    doc.setFontSize(14)
    doc.text(String( 'SKU:'+ entry.productSKU + '|VAL:' + entry.productValue+ '|ORG:'+ entry.organizationId?.toString().slice(-2)), 0, 17)
    // doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(entry.labelBarcode, 'image/png', 9, 20, 60, 28)
  } else if(entry.labelPrinterId === 'c') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(14)
    // doc.text(String(entry.product), 4, 8)
    // // doc.setFontSize(12)
    // // doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(entry.labelBarcode, 'image/png', 30, 25, 40, 26)
  } else if(entry.labelPrinterId === 'd') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(14)
    doc.text(String(entry.product), 4, 8)
    doc.setFontSize(12)
    doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(entry.labelBarcode, 'image/png', 30, 25, 40, 26)
  } else if(entry.labelPrinterId === 'e') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(14)
    doc.text(String(entry.product), 4, 8)
    doc.setFontSize(12)
    doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(entry.labelBarcode, 'image/png', 30, 25, 40, 26)
  } else if(entry.labelPrinterId === 'f') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(14)
    doc.text(String(entry.product), 4, 8)
    doc.setFontSize(12)
    doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(entry.labelBarcode, 'image/png', 30, 25, 40, 26)
  } else {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(18)
    doc.text(String(entry.product.replace("FOREVER ", "")), 0, 8)
    doc.setFontSize(14)
    doc.text(String( 'SKU: '+ entry.productSKU + ' | VAL: ' + entry.productValue+ ' | ORG: '+ entry.organizationId?.toString().slice(-2)), 0, 17)
    // doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(entry.labelBarcode, 'image/png', 9, 20, 60, 28)
  }
}

const serverPrinting = async (item) => {
  const exec = promisify(child_process.exec)
  const labelPrinters = {
    a: 'labelprinter-1',
    b: 'labelprinter-2',
    c: 'labelprinter-3',
    d: 'labelprinter-4',
    e: 'labelprinter-5',
    f: 'labelprinter-6',
  }
  let labelPrinter = 'labelprinter-2'
  if(labelPrinters[item.labelEntry]) {
    labelPrinter = labelPrinters[item.labelEntry]
  }

  let newResult = {}
  try {
    if(!existsSync(item.filePath)) {
      mkdirSync(item.filePath, { recursive: true })
    }
    await writeFile(`${item.filePath}/${item.fileName}`, Buffer.from(item.fileContent, 'base64'))

    const { stdout, stderr } = await exec(`lp -d ${labelPrinter} -o fit-to-page ${item.filePath}/${item.fileName}`);

    newResult['stdout'] = stdout
    newResult['stderr'] = stderr
  } catch(err: any) {
    newResult['stdout'] = item.fileContent
    newResult['stderr'] = err?.message || err?.data?.message || 'Error when printing via server side'
  }
  return newResult
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)
  const exec = promisify(child_process.exec)
  const pathName = body.pathName
  const filePath = `/root/storage/${pathName}`
  const fileName = body.fileName
  const labelEntries = body.labelEntries

  data['path'] = filePath
  data['name'] = fileName
  data['contents'] = []
  for(const [labelEntry, labelValues] of labelEntries) {
    const doc = new jsPDF({
      orientation: 'l',
      unit: 'mm',
      format: 'a8',
      putOnlyUsedFonts: true,
      compress: true
    })

    doc.addPage()

    let no = 2;
    for(let entry of labelValues.flat()) {
      for(let i = 0; i < Number(entry.qtyEntered || 0); i++) {
        labelByPrinter(doc, no, entry)

        no++
      }
    }

    doc.deletePage(1)
    doc.deletePage(Number(no) - 1)

    const fileContent = doc.output('dataurlstring')?.replace('data:application/pdf;filename=generated.pdf;base64,', '')
    data['contents'].push({
      label: labelEntry,
      content: fileContent
    })
    const resPrint = await serverPrinting({
      filePath,
      fileName: fileName.replace('-LABELS-', `-LABELPRINTER-${labelEntry}-`),
      fileContent,
      labelEntry
    })
    if(resPrint) {
      data['print_result'] = resPrint
    }
  }

  return data
})