global.TextDecoder = require('text-encoding').TextDecoder;
global.TextEncoder = require('text-encoding').TextEncoder;
const { WebSocketServer } = require('ws');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');

// Buat server WebSocket
const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function(ws) {
  console.log('Client terhubung');
  
  ws.on('message', function(message) {
    try {
      const data = JSON.parse(message.toString());
      
      if (data.action === 'cetak') {
        const tempFile = path.join(process.env.TEMP || '/tmp', 'print_data.dat');
        
        // Tulis file binary dari pesan
        try {
          // Konversi string hexadecimal ke buffer
          const printBuffer = Buffer.from(data.printData, 'hex');
          
          fs.writeFileSync(tempFile, printBuffer);
          console.log(`File cetak dibuat: ${tempFile}`);
        } catch (writeError) {
          console.error('Gagal membuat file cetak:', writeError);
          return ws.send(JSON.stringify({ 
            success: false, 
            error: 'Gagal menulis file: ' + writeError.message 
          }));
        }
        
        // Cetak ke printer
        const printCommand = `type "${tempFile}" > LPT1:`;
        console.log('Perintah cetak:', printCommand);
        
        exec(printCommand, (error, stdout, stderr) => {
          // Hapus file sementara
          try {
            fs.unlinkSync(tempFile);
            console.log('File cetak dihapus');
          } catch (unlinkError) {
            console.error('Gagal menghapus file:', unlinkError);
          }
          
          if (error) {
            console.error('Error pencetakan:', error);
            ws.send(JSON.stringify({ 
              success: false, 
              error: `Gagal mencetak: ${error.message}`
            }));
          } else {
            ws.send(JSON.stringify({ success: true }));
          }
        });
      }
    } catch (error) {
      console.error('Error memproses perintah:', error);
      ws.send(JSON.stringify({ 
        success: false, 
        error: 'Error memproses perintah: ' + error.message 
      }));
    }
  });
});

console.log('Server print berjalan di port 8080');