const  router = require('express').Router();
let ALevelResults = require('../models/studentALResult.model');
const mongoose = require("mongoose");

router.route('/add').post(async(req,res) =>{

    const results = await ALevelResults.findOne({
        student_id:req.body.student_id
    })

    console.log(req.body);

    const student_id = mongoose.Types.ObjectId(req.body.student_id);
    const year = req.body.year;
    const stream = req.body.stream;
    const Subjects = req.body.Subjects;
    // const subject01 = req.body.subject01;
    // const subject02 = req.body.subject02;
    // const subject03 = req.body.subject03;
    // const subject01Result = req.body.subject01Result;
    // const subject02Result = req.body.subject02Result;
    // const subject03Result = req.body.subject03Result;
    const generalEnglish = req.body.generalEnglish;
    const commonGeneralTest = req.body.commonGeneralTest;
    const image = req.body.image;

    const newResult = new ALevelResults({
        student_id,
        year,
        stream,
        Subjects,
        // subject01,
        // subject02,
        // subject03,
        // subject01Result,
        // subject02Result,
        // subject03Result,
        generalEnglish,
        commonGeneralTest,
        image,
    });



    if(!results){
        newResult.save().then(()=>{
            res.json('Item update!');
        })

    }
    else {
        ALevelResults.findById(req.body.student_id, function(err, details){
            if(!details){
                res.status(404).send("data is not found");
            }
            else {
                details.year = year;
                details.stream = stream;
                // details.subject01 = subject01;
                // details.subject02 = subject02;
                // details.subject03 = subject03;
                // details.subject01Result = subject01Result;
                // details.subject02Result = subject02Result;
                // details.subject03Result = subject03Result;
                details.generalEnglish = generalEnglish;
                details.commonGeneralTest = commonGeneralTest;
                details.image = image;

                details.save().then( () => {
                    res.json('results updated!');
                })
                    .catch(err => {
                        res.status(400).send("Update not possible");
                    });
            }
        })
    }
});

module.exports = router;