let libNodemailer = require('nodemailer');

fcf.module({
  name: "fcfSimpleAuthorization:templates/login-by-email.receive.js",
  dependencies: [],
  module: function(){
    var self = this;

    fcf.addException("FAILED_SEND_EMAIL", "Couldn't send email to the specified address");
    fcf.addException("FAILED_LOGIN_BY_EMAIL_UNKNOW_LOGIN", "The specified email or username is not registered in the system");

    return {
      receive: function(a_fields, a_files, a_request) {

        if (!fcf.application.getConfiguration().fcfSimpleAuthorization_enableLoginByEmail) {
          throw new fcf.Exception("OPERATION_NOT_SUPPORTED");
        }

        let skeep = false;
        let token = fcf.randStr(64);
        let email = undefined;
        return fcf.actions()
        .then(()=>{
          let value = a_fields.value;
          if (a_fields.value.indexOf("@") == -1)
            return fcf.application.getStorage().query(
                "SELECT id, email from \"" + fcf.application.getConfiguration().userProjectionName + "\" WHERE user = ${1}", 
                [a_fields.value],
                {roles: ["root"]}
              );
          else
            return fcf.application.getStorage().query(
              "SELECT id, email from \"" + fcf.application.getConfiguration().userProjectionName + "\" WHERE email = ${1}", 
              [a_fields.value],
              {roles: ["root"]}
            );
        })
        .then((a_records)=>{
          if (!a_records[0][0]){
            throw new fcf.Exception("FAILED_LOGIN_BY_EMAIL_UNKNOW_LOGIN");
            return;
          }
          email = a_records[0][0].email;
          return fcf.application.getStorage().query(
            "INSERT INTO ___fcfSimpleAuthorization___login_by_email (user, token, datetime) VALUES (${1}, ${2}, ${3})", 
            [a_records[0][0].id, token, fcf.dateFormat(new Date(), "Y-m-d H:i:s")], {roles: ["root"]});
        })
        .then(()=>{
          return fcf.application.render({
            template: fcf.application.getConfiguration().fcfSimpleAuthorization_loginByEmailTemplate,
            args: {
              token:    token,
            }
          });
        })
        .then((a_template)=>{
          let transporter = libNodemailer.createTransport({
            host: fcf.application.getConfiguration().mailService,
            port: 465,
            secure: true,
            auth: {
              user: fcf.application.getConfiguration().mailUser,
              pass: fcf.application.getConfiguration().mailPassword
            }
          });
          let options = {
            from:     fcf.application.getConfiguration().mailAddress,
            to:       email,
            subject:  fcf.t('Authorization'),
            html:     a_template.content,
          };
          transporter.sendMail(options, function(a_error, a_info){
            if (a_error) {
              a_act.error(new fcf.Exception("FAILED_SEND_EMAIL", {}, a_error));
              return;
            }
            a_act.complete();
          });
        })
      }
    }
  }
});
