export const sendToPrinter = async function (labelId, printDataArray, printer) { //retrieve parameters from carton-label-popup
  if (!printer) {
    throw 'Printer is not defined'
  }

  const chunkSize = 200 // The maximum quantity of printData items per chunks

  for (let i = 0; i < printDataArray.length; i += chunkSize) {
    const chunk = printDataArray.slice(i, i + chunkSize)
    let commands = '' // To accumulate printData for this chunk

    // Process each printData item in the current chunk
    for (const printData of chunk){
      let searchParams = new URLSearchParams()
      Object.entries(printData).forEach(obj => {
        if (typeof obj[1] != 'object') {
          searchParams.append(obj[0], obj[1])
        }
      })

      try {
        const response = await fetch(`label-command/${labelId}?${searchParams.toString()}`, {
          method: 'GET'
        })

        if (response.status !== 200) {
          throw `Error : Can't get label command from server (response: ${response.status})`
        }

        let command = await response.text()
        commands += command + ' '

      } catch (ex) {
        throw ex
      }
    }

    await printer.print(commands)
  }
}
