var express = require('express');
var router = express.Router();
var simulations = require('../lib/simulations.js');

var record = {};

router.post('/', function (req, res) {
  console.log(record);
  var simulation = new simulations.Simulation(
    req.body.numDevices, req.body.connectionProbability);
  console.log('Created simulation');
  record = simulation;
  res.render('simulation', simulation);
});

router.get('/', function (req, res) {
  res.render('simulation', record);
});

router.get('/info', function (req, res) {
  var dID = parseInt(req.query.deviceID);
  console.log('Got device id ' + dID);
  console.log('Type ' + typeof dID);
  for (var i = 0, len = record.devices.length; i < len; i++) {
    var device = record.devices[i];
    if (device.virtualIP === dID) {
      device.error = null;
      var response = { virtualIP: device.virtualIP, siblings: [], packets: [] };
      for (var j = 0, len2 = device.siblings.length; j < len2; j++) {
        response.siblings.push(device.siblings[j].virtualIP);
      }
      for (var j = 0, len2 = device.packets.length; j < len2; j++) {
        response.packets.push(device.packets[j]);
      }
      res.send(response);
      return;
    }
  }
  res.send({ error: 'No such device ' + dID });
});

router.put('/route', function (req, res) {
  console.log('Got route request. req.body = ');
  console.log(req.body);
  var source = req.body.source;
  var dest = req.body.destination;
  var msg = req.body.message;
  if (typeof source !== 'number') {
    source = parseInt(source);
  }
  if (typeof dest !== 'number') {
    dest = parseInt(dest);
  }
  // Simple and naive routing. The simulation object will handle it later.
  /*
  for (var i = 0, len = record.devices.length; i < len; i++) {
    if (record.devices[i].virtualIP === source || record.devices[i].virtualIP === dest) {
      record.devices[i].packets.push(new simulations.Packet(source, dest, msg));
    }
  }
  */
  var path = record.route(new simulations.Packet(source, dest, msg));
  for (var i = 0, len = path.length; i < len; i++) {
    path[i] = path[i].virtualIP;
  }
  console.log(path);
  // Send the route the packet took
  res.send(path);
});

module.exports = router;