const mongoose = require("mongoose");

const QueryHistory = mongoose.model("queryHistory");


/* * Gets called from the index.router.js
        * Records data in DB */
module.exports.saveQueries = (req, res, next) => {
    QueryHistory.create({ search_query: req.body.search_query, 
        timestamp : req.body.timestamp , user :req.body.user ,
        article_clicks : req.body.article_clicks , feedback_interactions : req.body.feedback_interactions,
        interaction_type : req.body.interaction_type},
        function(err, myobj) {
            if (err) { 
              return handleError(err); 
            } else { 
              res.sendStatus(200); 
            }
          }
    );
}

/* * Gets called from the index.router.js
* Returns the globalSearches*/
module.exports.globalQuerySearches = (req, res, next) => {
    QueryHistory.aggregate([
         {
            '$project': {
    
                'queryName': '$search_query', 
                'time': '$time',
                'article_clicks': '$article_clicks',
                'feedback_interactions' : '$feedback_interactions'

                
            },
            
        },
        {
            '$sort' : { 
                '_id' : -1 
            }
        },
        {
            '$skip': req.body.currentPage
        },
        {
            '$limit': 7
        },
    ]).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,
                querySearches: populatedResult
            });
        };
    });
};


/* * Gets called from the index.router.js
* Returns the globalSearches*/
module.exports.countQuerySearches = (req, res, next) => {
    QueryHistory.aggregate([
         {
            '$group': {
                '_id': null, 
                'count': { "$sum" : 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,
                searchcount: populatedResult
            });
        };
    });
};



