const mongoose = require("mongoose");

const ArticleInfos = mongoose.model("articleInfos");


/* * Gets called from the index.router.js
        * Records data in DB */
module.exports.updateArticleInfoClicks = (req, res, next) => {
    console.log("Article Title" + req.body.title + "\n Article ID: " + req.body.article_id + 
                "\n Query Name: " + req.body.search_query);
    // Find the document
    ArticleInfos.findOneAndUpdate(
        { search_query : req.body.search_query, article_title : req.body.title },
        { $inc : { article_clicks : 1},
            $set : { article_title : req.body.title, 
                     search_query : req.body.search_query,
                     article_id : req.body.article_id }
        }, 
        {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.updateArticleInfoRating = (req, res, next) => {
    console.log("Article Title" + req.body.title + "\n Article ID: " + req.body.article_id + 
    "\n Query Name: " + req.body.search_query);
    ArticleInfos.findOneAndUpdate(
        {search_query : req.body.search_query,  article_title : req.body.title },
        { $inc : { global_rating : req.body.rating},
            $set : { article_title : req.body.title, 
                        search_query : req.body.search_query ,
                        article_id : req.body.article_id }
        }, 
        {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.getArticleInfoProperties = (req, res, next) => {
    // Find the document
    var obj = {};
    var key = req.body["sortBy"];
    obj[key] = -1; // now obj === {'something' : 'value'}
    ArticleInfos.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,
                articleProperties: populatedResult
        });
    };
    });
}
