const express = require('express');
// const Joi = require('joi');
const app = express();

const io = require("socket.io-client");

const socket = io("http://socket.nelin.co:4949/", {
  reconnectionDelayMax: 10000
});


app.use(express.json());
 

// ------------------------------------------------------------
// testing APIs 
// ------------------------------------------------------------
// http://printer-manager.cafe-viuna.com:7878/api?clinet_id=11&printer_id=p1&url=https://viunaorder.avishost.com/pdf/18217.pdf
// http://localhost:7878/api?clinet_id=11&printer_id=p1&url=https://viunaorder.avishost.com/pdf/18217.pdf
// ------------------------------------------------------------
   

// socket event > connect
socket.on('connect', () => { 
  console.log('connect-client'); 
});

//



 
// -----------------------------------------------
app.get('/api', (req, res) => {

  const clinet_id  = req.query.clinet_id
  
 
  const printer_id = req.query.printer_id
  const url        = req.query.url
  const msg        = req.query.msg
  const order_id        = req.query.order_id
  const update_order_id        = req.query.update_order_id
  
 
  if(!order_id){
        socket.emit('showMsg', [clinet_id,msg]); 

  // socket event > off sendPrint
  socket.off('msg.....');

   
    res.json({
      code: 200,
      message: 'Socket.io show msg >> '+msg+'  Successfully!'
    }) 
  }
 
 
 
 
  if(order_id){
      socket.emit('sendOrder', [clinet_id, order_id,msg]); 

  // socket event > off sendPrint
  socket.off('sendOrder..');

   
    res.json({
      code: 200,
      message: 'Socket.io send order >> '+order_id+'  Successfully!'
    }) 
  }
  
  if(update_order_id){
      
       socket.emit('sendUpdate', [clinet_id, update_order_id,msg]);
  socket.off('sendOrder update..');

   
    res.json({
      code: 200,
      message: 'Socket.io send order update  >>'+update_order_id+'  Successfully!'
    }) 
  }


  if(printer_id){
      
        // emit the socket
  socket.emit('sendPrint', [clinet_id, printer_id, url]); 

  // socket event > off sendPrint
  socket.off('sendPrint');

   
    res.json({
      code: 200,
      message: 'Socket.io print command  Successfully!'
    }) 
  }
  
  
  // emit the socket
 
});

// -----------------------------------------------
// send route
// -----------------------------------------------
app.get('/send', (req, res) => {
    res.send('send');
});

   

 
// -----------------------------------------------
const port = process.env.PORT || 4848;
app.listen(port, () => console.log(`Listening on port ${port}..`));

