const express = require('express')
const router = express.Router()
const database = require('../database')
const passport = require('../config/passport')


router.get('/', (request, response) => {
  let { user } = request.body
  response.render('todos')
  .catch( (error) => {
  response.render('error', {message: error })
  })
})

router.get('/signup',(request, response) => {
  response.render('signup')

})

// router.post('/signup', (request, response) => {
//   let user = request.body
//   database.addUser(user)
//     .then( (user) => {
//       response.redirect('/users')
//     })
//     .catch( (error) => {
//       response.render('error', {message: error })
//     })
// })

router.post('/signup', (request, response) => {
    let user = request.body
    database.addUser(user)
      .then( (user) => {
        console.log(user, "yooooooo")
       console.log("doooode", user.name)
       const name = user.name
       const todosArray = []
       response.render("todos", {name, todosArray})
      })
      .catch( (error) => {
        response.render('error', {message: error })
     })
 })

router.get('/login', (request, response) => {
  response.render('login')
})

// router.post('/login',(request, response) => {
//   const {email, password } = request.body
//   database.authenticateUser(email, password)
//     .then(email => {
//       if (email) {
//         response.redirect('/users')
//       } else {
//         response.render('login', {
//           error: 'Email or Password Not Found'
//         })
//       }
//     })
//     .catch(error => {
//       response.render('error', {
//         error
//       })
//     })
// })


router.post('/login', (request, response) => {
  let user = request.body
  let userPassword = user.password
  let userEmail = user.email
  console.log("You entered: " + userEmail + ", with password: " + userPassword)

  database.checkIfUserExists(userEmail, userPassword)
    .then( (user) => {
      if(user.length === 0) {
        const message = "wrong password "
        response.render("login", {message})
      } else {
        // response.redirect(`/${user[0].name}`)
        const nameId = user[0].id
        const name = user[0].name
        database.getTodosByJoin(nameId)
          .then( results => {
            const todosArray = results
            response.render("todos", {name, todosArray})
          })
      }
    })
    .catch( reject => {
      console.log(reject)
    })
})

router.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

module.exports = router;
