const db = require("../models");
const User = db.users;
const Ad = db.ads
const passport = require('passport')
const bcrypt = require('bcrypt')

const initializePassport = require('../middleware/passport-config')

initializePassport(
    passport,
    email => User.findOne({ email: email }, function (err, adventure) {}),
    id => User.findById(id, function (err, adventure) {})
  )

  //check there is any connected user 
  exports.checkAuthenticated=(req, res, next)=>   {
  if (req.isAuthenticated()) {
    res.locals.login= req.isAuthenticated()
    res.locals.currentUser=req.session.passport.user
    
    return next()
  }

  res.redirect('/users/login')
}


exports.check=(req, res, next)=>   {
  if (req.isAuthenticated()) {
    res.locals.login= req.isAuthenticated()
  }
  return next()
}


//check if no user is connected
exports.checkNotAuthenticated = (req, res, next) =>  {
  if (req.isAuthenticated()) {
    return res.render('../views/user/user', {error : "you aren't connected"})
  }
  next()
}


//go to register page
exports.goToRegister = (req, res) =>{
    res.render('../views/user/register');
}
//go to user page
exports.goToUser = (req, res) =>{
  res.render('../views/user/user');
}


//register a user
exports.register = async (req, res) => {
  console.log(req.body)
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)
    req.body.password= hashedPassword 
    let us = await (new User(req.body)).save()
    res.redirect('/users/login')
  } catch (err){
    console.log(err.message)
    res.render('../views/user/register',{error: 'email déja utilisé'})
  }
}


//go to login page
exports.goToLogin = (req, res) =>{
  res.render('../views/user/login');
}



//find user's ads
exports.findUserads=  (req, res) => {
  
  Ad.find({id_user:req.session.passport.user}, function (err, result) {
    if (err) {
      console.log(err);
    } else {
      res.render('../views/user/user', { results: result })
    }
  });
};

//allow users to answer questions
exports.reponse=(req, res)=>{

  const idad = req.params.idad

  const idquestion = req.params.idquestion 

   Ad.findById(idad, function (err, ad) {
    
   ad.questions.find(({id}) => id==idquestion).reponse = req.body.reponse    

    Ad.findByIdAndUpdate(idad, ad, { runValidators: true })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: 'Cannot update Tutorial with id=${id}. Maybe Tutorial was not found!'
        });
      } else res.redirect("/show/"+data.slug+"/"+data.id)
    })
    .catch(err => {
      //res.redirect(req.originalUrl)
      res.send("not commpented");
      //res.status(500).send({
        //message: "Error updating Tutorial with id=" + id
      //});
    });
  });
}