const User = require('../models/user').User,
  List = require('../models/attendance').List,
  { exec } = require('child_process'),
  { decrypt } = require('../config/crypto'),
  nodemailer = require('nodemailer'),
  ejs = require('ejs'),
  pdf = require('html-pdf'),
  open = require('open'),
  { auth } = require('../config/email'),
  {
    emailAdmin,
    linuxPass,
    getLinuxId,
    createUser,
    createUserCluster,
    sshKey
  } = require('../helpers/user');

exports.add = (req, res) => {
  const id = req.params.id;

  User.findOne({ username: id }, (err, user) => {
    console.log(user);
    if (err)
      console.log(err);
    else {
      if (user.state === 2) {
        user.state = 1;
        user.save(err => {
          if (err) {
            console.log(err);
            return res.status(500);
          }
        });
      }
    }
    res.redirect('/admin/users');
  });
};

exports.remove = (req, res) => {
  const id = req.params.id;

  User.findOne({ username: id }, (err, user) => {
    console.log(user);
    if (err)
      console.log(err);
    else {
      if (user.state === 1) {
        user.state = 2;
        user.save(err => {
          if (err) {
            console.log(err);
            return res.status(500);
          }
        });
      }
    }
    res.redirect('/admin/users');
  });
};

exports.getUsers = (req, res) => {
  const page = req.params.id;

  User.find((err, docs) => {
    console.log(page);
    console.log(docs.length);

    res.render('admin/users', {
      message: req.flash('editProfile'),
      users: docs,
      user: req.user,
      conect: req.user
    });
  });
};

exports.getUsersList = (req, res) => {
  const page = req.params.id;

  User.find((err, docs) => {
    console.log(page);
    console.log(docs.length);

    ejs.renderFile(
      'views/admin/print.ejs',
      {
        message: req.flash('editProfile'),
        users: docs,
        user: req.user,
        conect: req.user
      },
      (err, result) => {
        // render on success
        if (result) {
          const html = result;
          const options = {
            format: 'Letter',
            orientation: 'landscape',
            border: {
              top: '1cm',
              right: '1cm',
              bottom: '1cm',
              left: '1cm'
            }
          };
          pdf
            .create(html, options)
            .toFile('./public/docs/account-request.pdf', (err, res) => {
              if (err) return console.log(err);
            });
        } else {
          // render or error
          res.end('An error occurred');
          console.log(err);
        }
      }
    );

    res.render('admin/list', {
      message: req.flash('editProfile'),
      users: docs,
      user: req.user,
      conect: req.user
    });
  });
};

// exports.getUsersListPrint = (req, res) => {
//   const page = req.params.id;
//
//   User.find((err, docs) => {
//     console.log(page);
//     console.log(docs.length);
//
//     // res.render('admin/list', {
//     //   message: req.flash('editProfile'),
//     //   users: docs,
//     //   user: req.user,
//     //   conect: req.user
//     // });
//     if (err)
//       console.log(err);
//     else {
//       ejs.renderFile(
//         'views/admin/print.ejs',
//         {
//           message: req.flash('editProfile'),
//           users: docs,
//           user: req.user,
//           conect: req.user
//         },
//         (err, result) => {
//           // render on success
//           if (result) {
//             const html = result;
//             const options = {
//               format: 'Letter',
//               orientation: 'landscape',
//               border: {
//                 top: '1cm',
//                 right: '1cm',
//                 bottom: '1cm',
//                 left: '1cm'
//               }
//             };
//             pdf
//               .create(html, options)
//               .toFile('./public/docs/account.pdf', (err, res) => {
//                 if (err) return console.log(err);
//               });
//           } else {
//             // render or error
//             res.end('An error occurred');
//             console.log(err);
//           }
//         }
//       );
//     }
//   });
//   res.redirect('/admin/users/list');
// };

exports.new = (req, res) => {
  const id = req.params.id;
  console.log(id);

  User.findOne({ username: id }, (err, user) => {
    if (err) {
      console.log(err);
      res.redirect('/');
    } else {
      user.state = 2;
      console.log(user);
      getLinuxId((err, uid) => {
        if (err) {
          console.log(err);
          res.redirect('/');
        } else {
          console.log(uid);
          createUser(uid, user, err => {
            if (err) {
              console.log(err);
              res.redirect('/');
            } else {
              console.log('here');
              User.update(
                { username: id },
                { state: user.state, uid: uid },
                (err, data) => {
                  if (err) {
                    console.log(err);
                    res.redirect('/');
                  } else {
                    sshKey(user, err => {
                      if (err) {
                        console.log(err);
                        res.redirect('/');
                      } else
                        res.redirect('/admin/users');
                    });
                  }
                }
              );
              // createUserCluster(uid, user, err => {
              //   if (err) {
              //     console.log(err);
              //     res.redirect('/');
              //   } else {
              //     console.log('CREATED');
              //     User.update(
              //       { username: id },
              //       { state: user.state, uid: uid },
              //       (err, data) => {
              //         if (err)
              //           console.log(err);
              //         else {
              //           sshKey(user, err => {
              //             if (err) console.log(err);
              //             else res.redirect('/admin/users');
              //           });
              //         }
              //       }
              //     );
              //   }
              // });
            }
          });
        }
      });
    }
  });
};

exports.activeUser = (req, res) => {
  const id = req.params.id;
  console.log(id);

  User.findOne({ username: id }, (err, user) => {
    if (err)
      console.log(err);
    else {
      console.log(user);
      user.state = 2;
      const passPath = 'echo ' +
        id +
        ':' +
        decrypt(user.linux) +
        ' | sudo chpasswd';

      User.update({ username: id }, { state: user.state }, (err, data) => {
        if (err)
          console.log(err);
        else {
          exec(passPath, (err, stdout, stderr) => {
            if (err) console.log(err);
            else if (stderr) console.log(stderr);
            else console.log(stdout);
          });
        }
      });
    }
  });

  res.redirect('/admin/users');
};

exports.inactiveUser = (req, res) => {
  const id = req.params.id;
  console.log(id);

  User.findOne({ username: id }, (err, user) => {
    if (err)
      console.log(err);
    else {
      console.log(user);
      user.state = 3;
      const passPath = 'echo ' + id + ':' + user.linux + ' | sudo chpasswd';

      User.update({ username: id }, { state: user.state }, (err, data) => {
        if (err)
          console.log(err);
        else {
          exec(passPath, (err, stdout, stderr) => {
            if (err)
              console.log(err);
            else if (stderr)
              console.log(stderr);
            else {
              console.log(stdout);
            }
          });
        }
      });
    }
  });

  res.redirect('/admin/users');
};

exports.getActiveUsers = (req, res) => {
  User.find({ state: 1 }, (err, docs) => {
    // console.log(docs);
    res.render('admin/users', {
      users: docs,
      user: req.user,
      conect: req.user
    });
  });
};

exports.getPendingUsers = (req, res) => {
  User.find({ state: 0 }, (err, docs) => {
    // console.log(docs);
    res.render('admin/users', {
      users: docs,
      user: req.user,
      conect: req.user
    });
  });
};

exports.getInactiveUsers = function(req, res) {
  User.find({ state: 3 }, function(err, docs) {
    // console.log(docs);
    res.render('admin/users', {
      users: docs,
      user: req.user,
      conect: req.user
    });
  });
};

exports.getUsersLinux = function(req, res) {
  const path = 'awk -F: \'/\\/home/ && ($3 >= 1000) {printf "%s:%s:%s\\n",$1,$3,$5}\'  /etc/passwd';
  // const path = 'awk -F: \'{printf "%s:%s:%s\\n",$1,$3,$5}\' /etc/passwd';

  exec(path, (err, stdout, stderr) => {
    if (err) {
      console.log('error en terminal');
    } else {
      const out = stdout.split('\n');

      // console.log(out[linuxUser].split(':'));
      for (let linuxUser = 0; linuxUser < out.length - 1; linuxUser++) {
        let linux = out[linuxUser].split(':');
        const user = new User({
          username: linux[0],
          name: linux[2].substring(0, linux[2].length - 3),
          uid: linux[1]
        });

        User.findOne({ uid: user.uid }, function(err, docs) {
          if (err) {
            console.log(err);
          } else if (docs === null) {
            user.state = 2;
            user.so = 1;

            user.save(function(err) {
              if (err) {
                console.log(err);
                return res.status(500);
              }
            });
          }
        });
      }
      res.redirect('/admin/users');
    }
  });
};

exports.Attendance = (req, res) => {
  List.find((err, docs) => {
    if (err)
      res.redirect('/');
    else
      res.render('attendance/attendance', {
        conect: req.user,
        users: docs
      });
    // console.log(docs);
  });
};

exports.getAttendance = (req, res) => {
  res.render('attendance/new', { conect: req.user });
};

exports.newAttendance = (req, res) => {
  const list = new List({
    user_id: req.body.user_id,
    name: req.body.name,
    last_name: req.body.last,
    profession: req.body.profession,
    email: req.body.email
  });

  list.save(function(err) {
    if (err) {
      console.log(err);
    }
  });
  res.redirect('/admin/attendance');
};

exports.emailContact = (req, res) => {
  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 + ' <' + req.body.email + '>',
        // to: 'alejorendon@utp.edu.co',
        to: data,
        subject: 'Contacto-Cluster Lovelace',
        text: req.body.text
      };
      transporter.sendMail(mailOptions, (err, res) => {
        if (err) console.log(err);
        else console.log(res);
      });
    }
  });
  res.redirect('/');
};
