const answerRoute = require('express').Router();
let answer = require('../models/answer.model');
const mongoose = require('mongoose');

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


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

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

answerRoute.route('/add').post(function(req, res) {
    const ans = new answer({
        answer_id: new mongoose.Types.ObjectId(),
        student_id : req.body.student_id,
        student_name :  req.body.student_name,
        lesson_no : req.body.lesson_no,
        no_of_questions : req.body.no_of_questions,
        question_text:  req.body.question_text,
        question_answer:req.body.question_answer,
        defult_mark:  req.body.defult_mark,
    });
    ans.save().then(ans =>{
        res.json('Item update!');
    })
        .catch(err =>{
            res.status(400).send("Update not possible");
        });
});

answerRoute.route('/update/:id').post((req, res) => {
    answer.findById(req.params.id,function(err, answer){
        if(!answer)
            req.status(404).send("data is not found");
        else {
            answer.lesson_no = req.body.lesson_no,
            answer.student_id = req.body.student_id,
            answer.student_name =  req.body.student_name,
            answer.no_of_questions = req.body.no_of_questions,
            answer.question_text =  req.body.question_text,
            answer.question_answer = req.body.question_answer,
            answer.defult_mark =  req.body.defult_mark
        }
        answer.save().then(answer =>{
            res.json('Item update!');
        })
            .catch(err =>{
                res.status(400).send("Update not possible");
            });
    });
});

answerRoute.route('/lessonNo/:id').get(function (req, res) {
    console.log("Product Item ID");
    console.log(req.params.id);
    let id = req.params.id;
    answer.find({"lesson_no" : id}, function (err, answer) {
        res.json(answer);
    });
});

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

module.exports = answerRoute;