'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _fsExtra = require('fs-extra');

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _crypto = require('crypto');

var _crypto2 = _interopRequireDefault(_crypto);

var _nodemailer = require('nodemailer');

var _nodemailer2 = _interopRequireDefault(_nodemailer);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _cli = require('../../../../cli');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function showHtml(res, req, info) {
  var resHtml = '';
  var page = _path2.default.join(__dirname + '/../../../views/users/forgot.html');
  if (_cli.coreUtils.file.exist(page)) {
    resHtml = _fsExtra2.default.readFileSync(page, 'utf8');
  }

  var template = _cli.Handlebars.compile(resHtml, { noEscape: true });

  var tmp = template({
    csrfToken: res.locals.csrfToken,
    config: JSON.stringify(_cli.config),
    express: {
      req: req,
      res: res
    },
    token: req.query.token,
    info: info
  });

  return res.send(tmp);
}

var route = function route(req, res) {
  var html;
  if (typeof req.query.email !== 'undefined' && req.query.email !== null) {
    _cli.User.utils.findByEmail(req.query.email, function (err, user) {
      if (err) {
        return res.status(200).json({ success: 1 });
      }

      _crypto2.default.randomBytes(20, function (err, buf) {
        var resetPasswordToken = buf.toString('hex');
        var forgotExpire = _cli.config.forgotExpire;

        _cli.User.operations.update({
          id: user.id,
          resetPasswordToken: resetPasswordToken,
          resetPasswordExpires: Date.now() + forgotExpire * 60 * 1000
        });

        var requestedUrl = req.protocol + '://' + req.get('Host') + '/abe/users/reset?token=' + resetPasswordToken;

        var smtp = _cli.config.smtp;
        var emailConf = _cli.config.users.email;
        html = emailConf.html || '';

        if (typeof emailConf.templateHtml !== 'undefined' && emailConf.templateHtml !== null) {
          var fileHtml = _path2.default.join(_cli.config.root, emailConf.templateHtml);
          if (_cli.coreUtils.file.exist(fileHtml)) {
            html = _fsExtra2.default.readFileSync(fileHtml, 'utf8');
          }
        }

        var template = _cli.Handlebars.compile(html, { noEscape: true });

        html = template({
          express: {
            req: req,
            res: res
          },
          forgotUrl: requestedUrl,
          siteUrl: req.protocol + '://' + req.get('Host'),
          user: user
        });

        if (typeof smtp === 'undefined' || smtp === null) {
          var transport = _nodemailer2.default.createTransport('direct', {});
          transport.sendMail({
            from: emailConf.from, // sender address
            to: user.email, // list of receivers
            subject: emailConf.subject, // Subject line
            text: emailConf.text.replace(/\{\{forgotUrl\}\}/g, requestedUrl), // plaintext body
            html: html.replace(/\{\{forgotUrl\}\}/g, requestedUrl) // html body
          }, console.error);

          showHtml(res, req, 'Check your inbox');
        } else if (typeof smtp !== 'string') {
          // create reusable transporter object using the default SMTP transport
          var transporter = _nodemailer2.default.createTransport('SMTP', smtp);

          // setup e-mail data with unicode symbols
          var mailOptions = {
            from: emailConf.from, // sender address
            to: user.email, // list of receivers
            subject: emailConf.subject, // Subject line
            text: emailConf.text.replace(/\{\{forgotUrl\}\}/g, requestedUrl), // plaintext body
            html: html.replace(/\{\{forgotUrl\}\}/g, requestedUrl) // html body
          };

          // send mail with defined transport object
          transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
              return console.log(error);
            }

            showHtml(res, req, 'Check your inbox');
            console.log('Message sent: ' + info.response);
          });
        }
      });
    });
  } else {
    showHtml(res, req, req.flash('info'));
  }
};

exports.default = route;