var express = require('express');
var router = express.Router();
var alerts = require('../model/alerts.js');
var globe = require('../model/globedata.js');
var cron = require('node-cron')
const path = require('path');
var WebSocket = require('ws')
var http = require('http')

/* GET home page. */
router.get('/display', function(req, res, next) {
  res.setHeader("Content-Type", "application/json");

  res.json(globe.getDisplayData());
});

router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../public/globe.html'));
});
const server = http.createServer(router);
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });


wss.on('connection', (ws) => {

  //connection is up, let's add a simple simple event
  ws.on('message', (message) => {

    //log the received message and send it back to the client
    console.log('received: %s', message);
  });
});
wss.broadcast = function broadcast(msg) {
  console.log(msg);
  wss.clients.forEach(function each(client) {
    client.send(msg);
  });
};
//start our server
server.listen(process.env.PORT || 8999, () => {
  console.log(`Server started on port ${server.address().port} :)`);
});

router.get('/alert/:uid', function(req, res, next) {
  const uid = req.params.uid
  res.setHeader("Content-Type", "application/json");
  res.json(alerts.getAlert(uid));
});

router.get('/alerts/dates', function(req, res, next) {
  res.json(alerts.getAlertDates());
});

var task = cron.schedule('* * * * *', () =>  {
  if(globe.getSettigns().timer.refreshTimer === 1) {
    wss.broadcast("new data is da")
  }
  const TEN_MINUTES = globe.getSettigns().timer.del*60*1000;
  const date = new Date();
  alerts.getAlertDates().forEach(ad => {
    var duration = Date.now() - ad.date.getTime();
    if (duration > TEN_MINUTES) {
      const todel = ad.uids;
      console.log(todel)
      delTimer(todel, ad.date)
    }
  })
});

function delTimer(todel, date){
  globe.delUids(todel)
  alerts.delAlerts(todel)
  alerts.delAlertDate(date)
}

router.post('/ws', async function(req, res, next) {
  for (const item of req.body.alerts) {
    const uid = alerts.addAlert(item.first_seen, item.srv_city_name, item.ip_version, item.action, item.pool_id, item.srv_continent_name, item.score, item.entity_val, item.vlan_id, item.cli2srv_bytes, item.cli_country_name, item.entity_id, item.srv_asn, item.l7_proto, item.is_cli_attacker, item.srv_name, item.srv_ip, item.proto, item.json, item.srv_country_name, item.community_id, item.alert_id, item.is_srv_attacker, item.srv_blacklisted, item.alerts_map, item.srv_os, item.cli_localhost, item.cli_asn, item.srv2cli_packets, item.cli2srv_packets, item.tstamp, item.cli_name, item.cli_continent_name, item.srv2cli_bytes, item.l7_cat, item.ifid, item.observation_point_id, item.srv_localhost, item.cli_port, item.cli_blacklisted, item.dns_last_query, item.is_flow_alert, item.srv_port, item.l7_master_proto, item.is_cli_victim, item.cli_ip, item.cli_city_name, item.cli_os, item.is_srv_victim);
    const src = item.srv_ip;
    const dest = item.cli_ip;
    if (typeof src !== 'undefined' || typeof dest !== 'undefined')
      await globe.addArc(src, dest, uid, item.srv_name, item.cli_name)
  }
  if(globe.getSettigns().timer.refreshTimer === 0) {
    wss.broadcast("new data is da")
  }
  res.sendStatus(200);
})

module.exports = router;
