const  router = require('express').Router();
let tutor = require('../models/tutor.user.model');
let userAccount = require('../models/userAccount.user.model');


const nodemailer = require('nodemailer');
const cred = require('../email-config/config');
const mongoose = require("mongoose");


////////////////////////////////////////////////////////////////////////////////////////
var transport = {
    host : 'smtp.gmail.com',
    auth : {
        user : cred.USER,
        pass : cred.PASS
    }
}

var transporter = nodemailer.createTransport(transport);

transporter.verify((error, success) => {
    if (error) {
        console.log(error);
    } else {
        console.log('Server is ready to take messages of User');
    }
});
/////////////////////////////////////////////////////////////////////////////////////////////

router.route('/').get((req,res) =>{
    tutor.find()
        .then(tutors => {
            console.log(tutors);
            res.json(tutors)
        })
        .catch(err => res.status(400).json('Eroor: '+ err));
});


router.route('/:id').get(function (req, res) {
    let id = req.params.id;
    //console.log("TutorId : " + id)
    tutor.findById(id).populate(['tutor_instituteIDList']).then(tutor => {
        ///console.log(tutor);
        res.json(tutor);
    }).catch(err => res.status(400).json('Eroor: '+ err));
});
// router.route('/:id').get(function (req, res) {
//     let id = req.params.id;
//     console.log("TutorId : " + id)
//     tutor.findById(id).populate("tutor_instituteIDList").then(tutor => {
//         console.log(tutor);
//         res.json(tutor);
//     }).catch(err => res.status(400).json('Eroor: '+ err));
// });


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

    console.log("Tutor Registration began")
    const tutor_name = req.body.tutor_name;
    const tutor_nic = req.body.tutor_nic;
    const tutor_email = req.body.tutor_email;
    const tutor_phone = req.body.tutor_phone;
    const tutor_address = req.body.tutor_address;
    const tutor_password = req.body.tutor_password;
    const tutor_gender = req.body.tutor_gender;
    const tutor_status = req.body.tutor_status;
    const tutor_image = req.body.tutor_image;
    const tutor_Stream = req.body.tutor_Stream;
    const tutor_subjects = req.body.tutor_subjects;
    const tutor_class_type = req.body.tutor_class_type;
    const tutor_main_district = req.body.tutor_main_district;
    const tutor_main_city = req.body.tutor_main_city;
    const tutor_medium = req.body.tutor_medium;
    const tutor_qualification = req.body.tutor_qualification;
    const tutor_student_count = 0;

    let instituteObjectIDList = [];

    req.body.tutor_instituteIDList.map(inst =>{
        instituteObjectIDList.push(mongoose.Types.ObjectId(inst));
    })

    const tutor_instituteIDList = instituteObjectIDList;

    //checking if the user is already exist in the database
    const user = await tutor.findOne({
        tutor_email:req.body.tutor_email
    })

    if(!user){
        const newTutor = new tutor({
            tutor_name,
            tutor_nic,
            tutor_email,
            tutor_phone,
            tutor_address,
            tutor_password,
            tutor_gender,
            tutor_status,
            tutor_image,
            tutor_Stream,
            tutor_subjects,
            tutor_class_type,
            tutor_main_district,
            tutor_main_city,
            tutor_medium,
            tutor_instituteIDList,
            tutor_qualification,
            tutor_student_count
        });
        newTutor.save()
            .then(tutor => {

                console.log("Inside the New User")
                console.log(tutor.id)
                const user_id = tutor.id.toString();
                const user_nic = req.body.tutor_nic;
                const user_email = req.body.tutor_email;
                const user_password = req.body.tutor_password;
                const user_type = "Tutor";

                const newUser = new userAccount({
                    user_id,
                    user_nic,
                    user_email,
                    user_password,
                    user_type

                });
                console.log(newUser);
                newUser.save()
                    .then(newUser =>{
                        console.log("Inside the Email Send part")
////////////////////////////////////////////////////////////////////////////////////
                        const content = `
                        Hi ${tutor_name},\n
                        You are Create a Tutor Account on SmartCoach.\n
                        You can verify your email address click on 'http://localhost:3000/AccountVerified/${newUser.id}'

                        Used your email address as username : ${user_email}
                        Thank You,
                        Team SmartCoach
                    `;

                        var mail = {
                            from: tutor_name,
                            to: user_email,
                            subject: 'Email Verification - Tutor',
                            text: content
                        }

                        transporter.sendMail(mail, (err, data) => {
                            if (err) {
                                res.json({
                                    msg: 'fail'
                                })
                            } else {
                                res.json({
                                    msg: 'success'
                                })
                            }
                        })
                        ;
/////////////////////////////////////////////////////////////////////////////////////

                    })
                    .catch(err =>res.status(400).json('Error: '+err));

                 res.json('Tutor Successfully Added....');




            })
            .catch(err =>res.status(400).json('Error: '+err));

    }
    else{
        return res.status(500).json('Email already exit');
    }


});


// router.route('/update/:id').post((req,res) =>{
//     userAccount.findById(req.params.id, function(err, details){
//         if(!details){
//             req.status(404).send("data is not found");
//         }
//         else {
//             details.confirmed = true;
//
//             details.save().then( () => {
//                     res.json('Item update!');
//             })
//                 .catch(err => {
//                     res.status(400).send("Update not possible");
//                 });
//         }
//     })
// });




module.exports = router;
