const db = require('../../db');
let map = function() {
  var d = new Date(this.updateTimestamp + 8 * 60 * 60 * 1000);
  var doub = function(num) {
    if ( num <= 9 ) return "0" + num;
    else return num;
  }
  emit({ date: d.getFullYear() + '' + doub(d.getMonth() + 1)   + '' + doub(d.getDate()), slotID: this.slotID, pubID: this.pubID }, {pv: this.pv, uids: this.uid});
};

let reduce = function(k, vals) {
  var result = { pv:0, uids: [] };
  var uniqs = [];
  for(var i in vals) {
    result.pv += vals[i].pv;
    result.uids = result.uids.concat(vals[i].uids)
  }
  return result;
};

module.exports = async function (query) {
  const statistics = await db.getCollection('statistics');
  return (await statistics.mapReduce(map, reduce, { query, out: { inline : 1 } } ));
}
