const  router = require('express').Router();
let tutor = require('../models/tutor.user.model');
let tutorRating = require('../models/TutorRatingAndReviews.model');
const mongoose = require("mongoose");


const express = require('express')
const request = require('request');

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



    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( async tutors => {


            let tutorReviewResultsFinal
            let tutorReviewResults = [];
             async function processData(callback) {

                  async function forLoopRun(callback6) {
                      let payload
                      let options
                     const promises = tutors.map(async (tutor) => {
                        await tutorRating.find({"tutor_id": tutor._id}).populate('tutor_id').then(async reviews01 => {
                             //console.log("Review Count " + reviews01.length);
                             if (reviews01.length > 0) {
                                 let reviewsList01 = [];

                                 const reviewPromises = reviews01.map(async function (oneReview) {
                                     reviewsList01.push(oneReview.review);
                                     return oneReview.review
                                 })

                                 const reviewsForTutor = await Promise.all(reviewPromises);
                                 await console.log(reviewsForTutor);

                                  async function getPrevMatches(cb) {
                                     options = {
                                         uri: 'http://localhost:5000/review_prediction_for_tutor',
                                         body: JSON.stringify(reviewsList01),
                                         method: 'POST',
                                         headers: {
                                             'Content-Type': 'application/json'
                                         }
                                     }

                                     request(options,  async function (error, response) {
                                         // console.log(error, response.body);
                                         //tutor.tutor_main_district = "Test";
                                         //tutorReviewResults.tutor_reviewValue = response.body;
                                         payload = {
                                             "tutor_id": 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_qualification": tutor.tutor_qualification,
                                             "tutor_reviewValue": JSON.parse(response.body).result,

                                         };
                                         await tutorReviewResults.push(payload);
                                         //console.log(payload)
                                         if (response.statusCode === 200){
                                             cb(payload);
                                         }


                                     });
                                 }
                                 await getPrevMatches( function (message777) {
                                     console.log(message777);
                                    // callback("Done : ProcessData");

                                 });

                                 // module.exports = {
                                 //     getPrevMatches: getPrevMatches
                                 // }


                                 //console.log(getPrevMatches);






                             }


                         })

                       return payload;
                     })
                       tutorReviewResultsFinal = await Promise.all(promises);
                      callback6("Get Return :" +tutorReviewResultsFinal);
                 }



                 await forLoopRun(async function (message2) {
                     console.log(message2);
                     callback("Done : ProcessData");

                 });


             }

            console.log("Last " +tutorReviewResults.length)
            await processData(   async function (message) {
                console.log(message);
                //console.log("Inside return Fuction");

            }).then(async r =>{
                console.log("Inside return Function");
                //await res.json(tutorReviewResults)
            }) ;
           console.log("End " +tutorReviewResults.length)
            res.json(tutorReviewResults)
        })
        .catch(err => res.status(400).json('Error: '+ err));
});



module.exports = router;
