const router = require('express').Router();
let tutor = require('../models/tutor.user.model');
let tutorRating = require('../models/TutorRatingAndReviews.model');
let tutorClasses = require('../models/createClass.model');
let ALResults = require('../models/studentALResult.model');
let classStudentList = require('../models/ClassStudentList.model');

const axios = require('axios');
//const request = require('request');


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

    let teacherReviewList = [];
    let reviewListWithScore = [];

    tutor.find({

        "tutor_Stream": {'$regex': req.body.selectedStream, '$options': 'i'},
        "tutor_subjects": {'$regex': req.body.selectedSubject, '$options': 'i'},
        "tutor_main_district": {'$regex': req.body.selectedDistrict, '$options': 'i'},
        "tutor_main_city": {'$regex': req.body.selectedCity, '$options': 'i'},
        "tutor_medium": {'$regex': req.body.selectedLanguage, '$options': 'i'},
        "tutor_class_type": {'$regex': req.body.selectedClassType, '$options': 'i'},

    })
        .then(tutors => {
            //console.log(tutors);

            tutors.reduce(async (promise, tutor, idx) => {
                await promise;
                let classCount = 0;
                let studentCount = 0;
                await tutorRating.find({"tutor_id": tutor._id}).then(async (reviews) => {
                    //console.log("i : " + JSON.stringify(reviews));

                   await tutorClasses.find({"tutor_id": tutor._id}).then(async (tutorOneClass) =>{
                        classCount = tutorOneClass.length;
                        console.log("Class Count : " + classCount);

                       // let oneClassCount = 0
                       //
                       //  if(tutorOneClass.length > 0){
                       //      tutorOneClass.reduce(async (promise, tutorOneCl, idx2) =>{
                       //          await promise;
                       //          await classStudentList.find({"class_id": tutorOneCl._id}).then(  async (stdCount)=>{
                       //              oneClassCount = oneClassCount  + stdCount.length;
                       //
                       //              if(idx2 === stdCount.length - 1){
                       //                  studentCount = oneClassCount;
                       //              }
                       //
                       //          })
                       //      }, Promise.resolve())
                       //  }

                    })


                    console.log("idx : " + idx);
                    // console.log("tutor : " + tutors);
                    const teacherReview = {
                        "teacher": tutor._id,
                        "tutor_name": tutor.tutor_name,
                        "tutor_nic": tutor.tutor_nic,
                        "tutor_email": tutor.tutor_email,
                        "tutor_phone": tutor.tutor_phone,
                        "tutor_address": tutor.tutor_address,
                        "tutor_password": tutor.tutor_password,
                        "tutor_gender": tutor.tutor_gender,
                        "tutor_status": tutor.tutor_status,
                        "tutor_image": tutor.tutor_image,
                        "tutor_Stream": tutor.tutor_Stream,
                        "tutor_subjects": tutor.tutor_subjects,
                        "tutor_class_type": tutor.tutor_class_type,
                        "tutor_main_district": tutor.tutor_main_district,
                        "tutor_main_city": tutor.tutor_main_city,
                        "tutor_medium": tutor.tutor_medium,
                        "tutor_registered_date": tutor.createdAt,
                        "tutor_class_count": classCount,
                        "tutor_qualification": tutor.tutor_qualification,
                        "tutor_student_count": tutor.tutor_student_count,
                        "review": reviews.map(review => review.review),
                        "ratings": reviews.map(review => review.rating)
                    }
                    //teacherReviewList.indexOf(teacherReview) === -1 ? teacherReviewList.push(teacherReview) : null;
                    let index = teacherReviewList.findIndex(x => x.teacher === tutor._id);
                    if (index === -1) {
                        teacherReviewList.push(teacherReview);
                    }

                    if (idx === tutors.length - 1) {

                        //console.log(teacherReviewList);

                        teacherReviewList.reduce(async (promise, teacherReview, idx, teacherReviewList) => {
                            await promise;
                            console.log("length" + teacherReview.review.length);
                            if (teacherReview.review.length > 0) {
                                let options = {
                                    uri: 'http://localhost:5000/review_prediction_for_tutor',
                                    body: JSON.stringify(teacherReview.review),
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json'
                                    }
                                }

                                let response = await axios.post(options.uri, options.body);
                                let TotalRating = 0;
                                teacherReview.ratings.map(rate =>{
                                    TotalRating = TotalRating + Number(rate)
                                })
                                    const temp = {
                                        "teacher": teacherReview.teacher,
                                        "tutor_name": teacherReview.tutor_name,
                                        "tutor_nic": teacherReview.tutor_nic,
                                        "tutor_email": teacherReview.tutor_email,
                                        "tutor_phone": teacherReview.tutor_phone,
                                        "tutor_address": teacherReview.tutor_address,
                                        "tutor_password": teacherReview.tutor_password,
                                        "tutor_gender": teacherReview.tutor_gender,
                                        "tutor_status": teacherReview.tutor_status,
                                        "tutor_image": teacherReview.tutor_image,
                                        "tutor_Stream": teacherReview.tutor_Stream,
                                        "tutor_subjects": teacherReview.tutor_subjects,
                                        "tutor_class_type": teacherReview.tutor_class_type,
                                        "tutor_main_district": teacherReview.tutor_main_district,
                                        "tutor_main_city": teacherReview.tutor_main_city,
                                        "tutor_medium": teacherReview.tutor_medium,
                                        "tutor_qualification": teacherReview.tutor_qualification,
                                        "tutor_registered_date": teacherReview.tutor_registered_date,
                                        "tutor_class_count": teacherReview.tutor_class_count,
                                        "tutor_student_count": teacherReview.tutor_student_count,
                                        "tutor_reviewValue": response.data.result,
                                        "tutor_avg_rating" : Number(TotalRating/teacherReview.ratings.length),
                                        "tutor_review_count" : teacherReview.review.length
                                    }

                                    let index = await reviewListWithScore.findIndex(x => x.teacher === teacherReview.teacher);
                                    if (index === -1) {
                                        reviewListWithScore.push(temp);
                                    }
                                    console.log(response.data.result);



                            } else {

                                const temp = {
                                    "teacher": teacherReview.teacher,
                                    "tutor_name": teacherReview.tutor_name,
                                    "tutor_nic": teacherReview.tutor_nic,
                                    "tutor_email": teacherReview.tutor_email,
                                    "tutor_phone": teacherReview.tutor_phone,
                                    "tutor_address": teacherReview.tutor_address,
                                    "tutor_password": teacherReview.tutor_password,
                                    "tutor_gender": teacherReview.tutor_gender,
                                    "tutor_status": teacherReview.tutor_status,
                                    "tutor_image": teacherReview.tutor_image,
                                    "tutor_Stream": teacherReview.tutor_Stream,
                                    "tutor_subjects": teacherReview.tutor_subjects,
                                    "tutor_class_type": teacherReview.tutor_class_type,
                                    "tutor_main_district": teacherReview.tutor_main_district,
                                    "tutor_main_city": teacherReview.tutor_main_city,
                                    "tutor_registered_date": teacherReview.tutor_registered_date,
                                    "tutor_class_count": teacherReview.tutor_class_count,
                                    "tutor_student_count": teacherReview.tutor_student_count,
                                    "tutor_medium": teacherReview.tutor_medium,
                                    "tutor_qualification": teacherReview.tutor_qualification,
                                    "tutor_reviewValue": 0,
                                    "tutor_avg_rating" : 0
                                }

                                //reviewListWithScore.push(temp);
                                //reviewListWithScore.indexOf(temp) === -1 ? reviewListWithScore.push(temp) : null;

                                let index = reviewListWithScore.findIndex(x => x.teacher === teacherReview.teacher);
                                if (index === -1) {
                                    reviewListWithScore.push(temp);
                                }
                            }
                            if (idx === teacherReviewList.length - 1) {

                                res.json(reviewListWithScore)
                               // console.log(reviewListWithScore);
                            }

                        }, Promise.resolve())

                    }

                });
            }, Promise.resolve())
            //console.log("Return from here");
        })
        .catch(err => res.status(400).json('Error: ' + err));
});



module.exports = router;