require('dotenv').config()

const dgram = require('dgram');
const server = dgram.createSocket('udp4');
const app = require('./app')

const PORT = process.env.PORT 

server.on('error', (err) => {
  console.log(`Server error:\n${err.stack}`);
  server.close();
});

server.on('message', async (msg, rinfo) => {
  console.log(`Server got: ${msg} from ${rinfo.address}:${rinfo.port}`);

  const strMsg = msg.toString()
  const categories = await app(strMsg)

  let result = {}

  if (categories) 
  result = {
    result: categories
  }

  server.send(JSON.stringify(result), rinfo.port, rinfo.address, (err) => {
    if (err) server.close();
  });
});

server.on('listening', () => {
  const address = server.address();
  console.log(`Server listening ${address.address}:${address.port}`);
});

server.bind(PORT);

// Response
// {"result":[10009]} 