var express = require('express');
var router = express.Router();
// --------------------------------------------------------------------------------------
router.get('/', function(req, res, next) {
  res.render('inst_roaming', { title: 'Ukazkove rozhrani pro vyhledavani nad radius logy' });
});
// --------------------------------------------------------------------------------------
router.post('/search', function(req, res, next) {
  search(req, res, respond);
});
// --------------------------------------------------------------------------------------
function search(req, res) {
  
  // TODO - timestamp
  
  min_date = new Date("2015-04-23T00:00:00Z");
  max_date = new Date(min_date.getTime() + 86400000);

  req.db.logs.aggregate(
  [ 
  { 
    $match : 
      { 
        timestamp : 
          { 
            $gte : min_date,         // TODO
            $lt : max_date 
          }, 
        result : "OK",          // match only successful logins
        visinst : 
          { 
            $ne : "UNKNOWN"       // no unknown institutions
          }
      } 
  },  
  { 
    $group :                    // group by pair [visinst, csi ] - normalization by mac address
      {
        _id : 
          { 
            visinst : "$visinst", 
            csi : "$csi" 
          } 
      } 
  },
  { 
    $project : 
    { 
      "_id.visinst" : 1              // we want only visinst
    } 
  }, 
  { 
    $group :                   // group by visinst
      { 
        _id : 
          { 
            visinst : "$_id.visinst" 
          }, 
        count : 
          { 
            $sum : 1           // count number of current visinst
          } 
      } 
  }, 
  { 
    $sort :                    // sort from lowest to highest
    { 
      count : 1
    } 
  }   
  ],
    function(err, items) {
      if(err == null)
        items = filter(items);

      respond(err, items, res);
  });
}
// --------------------------------------------------------------------------------------
function respond(err, items, res) {
  if(err) {
    console.log(err);
    res.send(err);
    return;
  }
  
  res.json(items);
}
// --------------------------------------------------------------------------------------
function filter(items)
{
  dict = {};

  for(var item in items) {
    var key = items[item];
    dict[key._id.visinst] = key.count    // save count to visinst
  }

  return dict;
}
// --------------------------------------------------------------------------------------
module.exports = router;

var express = require('express');
var router = express.Router();
const aqp = require('api-query-params').default;    // uses ES6
// --------------------------------------------------------------------------------------
// get roaming data for organisations most using roaming
// timestamp, [inst_name, provided_count]
// --------------------------------------------------------------------------------------
router.get('/', function(req, res, next) {
  var qs = req.url.substr(2);   // remove '/?'

  var query = aqp(qs, {         // parse query string
    whitelist : [ 'timestamp', 'inst_name', 'used_count' ]       // whitelist collection keys
  });

  if(query.filter.timestamp == undefined) {    // do not search if timestamp is not defined
    res.end("timestamp must be defined!");
    return;
  }

  // validation
  var keys = query.filter.timestamp;
  var range = [];

  for(var key in keys) {
    range.push(keys[key]);      // for further processing

    if(isNaN(Date.parse(keys[key]))) {    // invalid date
      res.end("invalid date: " + keys[key]);
      return;
    }
  }
  
  // valid cases for timestamp
  //
  // = exactly one day
  // = range from, to
  //
  // TODO - distinct date at 00:00:00:000 and other dates
  // needs to be implemented?
  if(typeof(query.filter.timestamp) == "object" && Object.keys(query.filter.timestamp).length > 1) {  // range
    if(Math.abs(range[0] - range[1]) % 86400000 == 0) {     // exact range of days
      search_days(req, res, respond, query);
    }
    else {  // another range
      //search_interval(req, res, respond, query);
      // TODO
    }
  }
  else {    // one day only
    search_days(req, res, respond, query);
  }
});
// --------------------------------------------------------------------------------------
// send data to user
// --------------------------------------------------------------------------------------
function respond(err, items, res) {
  if(err) {
    console.log(err);
    res.send(err);
    return;
  }
  
  res.json(items);
}
// --------------------------------------------------------------------------------------
// search database for specified data
// timestamp matches specific day or range of days
// --------------------------------------------------------------------------------------
function search_days(req, res, respond, query) {
  query.filter.provided_count = query.used_count || { "$exists" : true };   // make sure used count is set

  req.db.roaming.find(query.filter, { _id : 0, timestamp : 0}, function(err, items) {
    respond(err, items, res);
  });
}
// --------------------------------------------------------------------------------------
module.exports = router;

update route to use api-query-params