const mongoose = require("mongoose");

const ClickEntries = mongoose.model("clickEntries");


/* * Gets called from the index.router.js
        * Records data in DB */
module.exports.saveClicks = (req, res, next) => {

  ClickEntries.create({article_id: req.body.article_id,
    title: req.body.title, rating : req.body.click , 
    user :req.body.user, search_query: req.body.search_query},
    function(err, myobj) {
      if (err) { 
        res.sendStatus(404); 
      } else { 
        res.sendStatus(200); 
      }
    });

}

    /* * Gets called from the index.router.js
        * Returns the number of clicks per query */
module.exports.articleClicks = (req, res, next) => {
    ClickEntries.aggregate([
      {
        '$group': {
          '_id': '$search_query', 
          'clicks': {
            '$sum': 1
          }
        }
      },
      {
        '$project': {
          '_id': 0, 
          'queryName': '$_id', 
          'articleClicks': '$clicks'
        }
      },
      {
        '$sort' : { 'articleClicks' : -1 }
      }
      ]).exec((err, populatedResult) => {
        if(err) {
          res.sendStatus(404); 
        } else {
            //use this log to debug the JSON ouput
            // console.log(JSON.stringify(populatedResult));
            //res.status(200).send(populatedResult);
            return res.status(200).json({
                status: true,
                clicks: populatedResult
            });
        };
      });
  };