const User = require('../models/user').User,
  nodemailer = require('nodemailer'),
  { auth } = require('../config/email.js'),
  { emailAdmin } = require('../helpers/user'),
  { encrypt } = require('../config/crypto');

// exports.login = function(req, res) {
//   // console.log(req);
//   const user = new User({
//                           username: req.body.username,
//                           password: req.body.password,
//                         });
//   console.log(user);
//
//   User.findOne({username: user.username}, function(err, docs) {
//     if(err) {
//       console.log(err);
//     } else if (docs !== null) {
//       console.log('Existe el usuario');
//     }
//   });
//   res.redirect('/login');
// };

exports.newUser = function(req, res) {
  let state = 0;
  let email = '';

  // Si no existen usuarios en la BD
  User.find(function(err, docs) {
    if (docs.length === 0)
      state = 1;
    else {
      for (user in docs) {
        // console.log(docs[user].email);
        email += docs[user].email;
      }
    }
    console.log(email);
  });

  User.findOne(
    {
      $or: [{ email: req.body.email }, { username: req.body.username }]
    },
    function(err, user) {
      if (err) return done(err);
      if (user) {
        // console.log(user);
        console.log('Ya existe !!!');
        if (user.email === req.body.email)
          req.flash(
            'signupMessage',
            'Existe un registro con el Correo Electrónico ingresado'
          );
        if (user.username === req.body.username)
          req.flash(
            'signupMessage',
            'Existe un registro con el Nombre de Usuario ingresado'
          );
        res.redirect('/signup');
      } else if (req.body.password !== req.body.confirmPassword) {
        console.log(user);
        console.log('No coincide la contraseña');
        req.flash('signupMessage', 'No coincide la contraseña');
        res.redirect('/signup');
      } else {
        const newUser = new User();
        newUser.state = state;
        newUser.user_id = req.body.user_id;
        newUser.username = req.body.username;
        newUser.name = req.body.name;
        newUser.last_name = req.body.last_name;
        newUser.email = req.body.email;
        newUser.profession = req.body.profession;
        newUser.password = newUser.generateHash(req.body.password);
        newUser.linux = encrypt(req.body.password);
        newUser.connection = new Date();
        newUser.text = req.body.text;
        console.log(newUser);
        newUser.save(function(err) {
          if (err) {
            console.log(err);
            throw err;
            res.redirect('/signup');
          } else {
            emailAdmin((err, data) => {
              if (err)
                console.log(err);
              else {
                const transporter = nodemailer.createTransport(
                  'smtps://' + auth.user + ':' + auth.pass + '@smtp.gmail.com'
                );
                const mailOptions = {
                  from: (
                    req.body.name +
                      ' ' +
                      req.body.last_name +
                      ' <' +
                      req.body.email +
                      '>'
                  ),
                  to: data,
                  subject: 'Contacto-Cluster Lovelace', // text: req.body.text,
                  html: (
                    'Sr Admin, solicitud de cuenta pendiente: <br />' +
                      '<hr />' +
                      '<b>Username: </b>' +
                      req.body.username +
                      '<br />' +
                      '<b>Nombre: </b>' +
                      req.body.name +
                      ' ' +
                      req.body.last_name +
                      '<br />' +
                      '<b>Código: </b>' +
                      req.body.user_id +
                      '<br />' +
                      '<b>Correo Electrónico: </b>' +
                      req.body.email +
                      '<br /><hr />' +
                      '<b>Justificación: </b><br />' +
                      '<i>' +
                      req.body.text +
                      '</i>'
                  )
                };
                transporter.sendMail(mailOptions, (err, res) => {
                  if (err) console.log(err);
                  else console.log(res);
                });
              }
            });
            res.redirect('/');
          }
        });
      }
    }
  );
};
