const mongoose = require("mongoose");

const QueryInfos = mongoose.model("queryInfos");


/* * Gets called from the index.router.js
        * Records data in DB */
module.exports.updateQuerySearches = (req, res, next) => {
    // Find the document
    QueryInfos.findOneAndUpdate(
        { search_query : req.body.search_query },
        { $inc : { query_searches : 1} }, {upsert : true, setDefaultsOnInsert : true},
        function(err, myobj) {
            if (err) { 
                res.sendStatus(404); 
            } else { 
                res.sendStatus(200); 
            }
          }
    );
}

/* * Gets called from the index.router.js
        * Records data in DB */
module.exports.updateQueryArticleClicks = (req, res, next) => {
    // Find the document
    QueryInfos.findOneAndUpdate(
        { search_query : req.body.search_query },
        { $inc : { article_clicks : 1} }, {upsert : true, setDefaultsOnInsert : true},
        function(err) {
            if (err) {
                res.sendStatus(404); 
            } else {
                res.sendStatus(200); 
            }
        }
    );
}

/* * Gets called from the index.router.js
* Records data in DB */
module.exports.updateQueryArticleFeedbacks = (req, res, next) => {
    // Find the document
    QueryInfos.findOneAndUpdate(
        { search_query : req.body.search_query },
        { $inc : { feedback_interactions : 1} }, {upsert : true, setDefaultsOnInsert : true},
        function(err) {
            if (err) {
                res.sendStatus(404); 
            } else {
                res.sendStatus(200); 
            }
        }
    );
}

/* * Gets called from the index.router.js
* Records data in DB */
module.exports.getGlobalProperties = (req, res, next) => {
    // Find the document
    var obj = {};
    var key = req.body["sortBy"];
    obj[key] = -1; // now obj === {'something' : 'value'}
    QueryInfos.find(
        {},
        {}
    ).sort(obj).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,
                globalProperties: populatedResult
        });
    };
    });
}

