const questionRouter = require('express').Router();
let Question = require('../models/question.model');
const mongoose = require('mongoose');

questionRouter.route('/').get(function(req, res) {
    Question.find(function(err, questions) {
        if (err) {
            console.log(err);
            res.render('index');
        } else {
            res.json(questions);
        }
    });
});


questionRouter.route('/:id').get(function (req, res) {
    let id = req.params.id;
    Question.findById(id, function (err, question) {
        res.json(question);
    });
});

questionRouter.route('/questionId/:id').get(function (req, res) {
    console.log("Question ID");
    console.log(req.params.id);
    let id = req.params.id;
    Question.find({"_id" : id}, function (err, question) {
        res.json(question);
    });
});

questionRouter.route('/add').post(function(req, res) {
    const question = new Question({
        question_id: new mongoose.Types.ObjectId(),
        lesson_no : req.body.lesson_no,
        lesson_name : req.body.lesson_name,
        question_text:  req.body.question_text,
        question_answer:req.body.question_answer,
        defult_mark:  req.body.defult_mark,
        time_createdby:  req.body.time_createdby,
        time_modifiedby: req.body.time_modifiedby,
        general_feedback: req.body.general_feedback
    });
    question.save().then(question =>{
        res.json('Item update!');
    })
        .catch(err =>{
            res.status(400).send("Update not possible");
        });
});

questionRouter.route('/update/:id').post((req, res) => {
    Question.findById(req.params.id,function(err, question){
        if(!question)
            req.status(404).send("data is not found");
        else {
            question.lesson_no = req.body.lesson_no;
            question.lesson_name = req.body.lesson_name;
            question.question_text = req.body.question_text;
            question.question_answer = req.body.question_answer;
            question.defult_mark = req.body.defult_mark;
            question.q_type = req.body.q_type;
            question.time_modifiedby = req.body.time_modifiedby;
            question.general_feedback = req.body.general_feedback;

        }
        question.save().then(question =>{
            res.json('Item update!');
        })
            .catch(err =>{
                res.status(400).send("Update not possible");
            });
    });
});

questionRouter.route('c').get(function (req, res) {
    console.log("Product Item ID");
    console.log(req.params.id);
    let id = req.params.id;
    Question.find({"lesson_no" : id}, function (err, product) {
        res.json(product);
    });
});

questionRouter.route('/delete/:id').delete((req, res) => {
    Question.findByIdAndDelete(req.params.id)
        .then(() => res.json('Product Deleted.'))
        .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = questionRouter;