require('dotenv').config()

const dgram = require('dgram');
const app = require('./app')
const bodyParser = require('body-parser')
const cron = require('./cron')
const express = require('express')

const httpServer = express()
httpServer.use(bodyParser.json()) // for parsing application/json
httpServer.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
cron()

const UDP_PORT = process.env.UDP_PORT 
const HTTP_PORT = process.env.HTTP_PORT 

const server = dgram.createSocket('udp4');


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()
  let categories = await app(strMsg)

  let result = {}

  categories = categories.map(category => parseInt(category))

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

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

server.bind(UDP_PORT);

httpServer.post('/', async (req, res) => {
  try {
    const { fqdn } = req.body

    const categories = await app(fqdn)
  
    let result = {}
  
    if (categories) 
    result = {
      result: categories
    }
  
    res.status(200).json(JSON.stringify(result))
  } catch (err) {
    res.status(500).json(err)
  }
  
})

httpServer.listen(HTTP_PORT, () => {
  console.log('HTTP server listening 3333')
})

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