const tools = require('./tools/general');
const telegrambot = require('./telegram/telegrambot');

require('./config/config');

const Email = require('email-templates');

const i18n = require('i18n');

const {ObjectID} = require('mongodb');
const {Settings} = require('./models/settings');
const {TemplEmail} = require('./models/templemail');
const {Discipline} = require('./models/discipline');

const previewEmail = require('preview-email');
const nodemailer = require('nodemailer');

const OrdersCart = require('./models/orderscart');

const {MyEvent} = require('./models/myevent');
const {MailingList} = require('./models/mailinglist');
const {Newstosent} = require('./models/newstosent');

const server_constants = require('./tools/server_constants');

const shared_consts = require('./tools/shared_nodejs');

const {User} = require('./models/user');

const transport_preview = nodemailer.createTransport({
  jsonTransport: true,
});

function checkifSendEmail() {
  return process.env.SEND_EMAIL === '1';
  //return false;
}

module.exports = {
  sendEmail_base_e_manager: function(idapp, template, to, mylocalsconf, replyTo, transport, previewonly) {
    this.sendEmail_base(template, to, mylocalsconf, replyTo, transport, previewonly);

    this.sendEmail_base(template, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '', transport, previewonly);

    if (tools.isManagAndAdminDifferent(idapp)) {
      const email = tools.getManagerEmailByIdApp(idapp);
      this.sendEmail_base(template, email, mylocalsconf, '', transport, previewonly);
    }

  },

  sendEmail_base: function(template, to, mylocalsconf, replyTo, transport, previewonly) {

    if (to === '')
      return false;
    // console.log('mylocalsconf', mylocalsconf);

    // console.log("check EMAIL :" + checkifSendEmail());

    if (replyTo === '')
      replyTo = mylocalsconf.dataemail.email_reply;

    const paramemail = {
      message: {
        from: mylocalsconf.dataemail.from, // sender address
        headers: {
          'Reply-To': replyTo,
        },
      },
    };

    if (previewonly === undefined) {
      paramemail.preview = !checkifSendEmail();
      paramemail.send = checkifSendEmail();
    } else {
      paramemail.preview = previewonly;
      paramemail.send = !previewonly;
    }

    // if (!transport) {
    //   transport = this.getTransport(mylocalsconf);
    // }

    // console.log('1 . transport', transport);

    if (transport) {
      paramemail.transport = transport;
    } else {
      paramemail.transport = this.getTransport(mylocalsconf);
      /*
      // console.log('1b . transport gmail');
      paramemail.transport = {
        service: 'gmail',
        auth: {
          user: tools.getEmailByIdApp(mylocalsconf.idapp),
          pass: tools.getPwdByIdApp(mylocalsconf.idapp)
        }
      }*/
    }

    // console.table(paramemail.transport);

    // console.log('2 . paramemail.transport', paramemail.transport);
    // console.log('user', tools.getEmailByIdApp(mylocalsconf.idapp));
    // console.log('pass', tools.getPwdByIdApp(mylocalsconf.idapp));

    // console.log('paramemail', paramemail);

    const email = new Email(paramemail);

    console.log(' *** Invia Email a ' + to, 'template', template);

    return email.send({
      template: template,
      message: {
        to: to,
      },
      locals: mylocalsconf,
    }).then((ris) => {
      // console.log('ris EMAIL', ris);
      return !!ris;
    }).catch((err) => {
      console.error('sendEmail_base Error: ', err);
      return false;
    });
  },

  sendEmail_Normale: async function(to, subject, html, replyTo) {

    // setup e-mail data with unicode symbols
    var mailOptions = {
      from: tools.getEmailByIdApp(mylocalsconf.idapp), // sender address
      dataemail: await this.getdataemail(idapp),
      to: to,
      generateTextFromHTML: true,
      subject: subject,
      html: html,
    };

    if (replyTo)
      mailOptions['reply-to'] = replyTo;

    const smtpTransport = this.getTransport(mylocalsconf);

    if (process.env.SEND_EMAIL === '1') {
      // console.log("SEND EMAIL...");
      // send mail with defined transport object
      smtpTransport.sendMail(mailOptions, function(error, response) {
        if (error) {
          console.log('Email Inviata ERRORE RISPOSTA: ' + error);
        } else {
          // console.log("Email Inviata RISPOSTA: " + response);
        }
      });
    } else {
      if (process.env.PROVA_EMAIL_TEMPLATE !== '1')
        previewEmail(mailOptions).then(console.log).catch(console.error);
      else
        transport_preview.sendMail(mailOptions).then(console.log).catch(console.error);
    }
  },

  getlinkReg: function(idapp, idreg) {
    const strlinkreg = tools.getHostByIdApp(idapp) + process.env.LINKVERIF_REG + `/?idapp=${idapp}&idlink=${idreg}`;
    return strlinkreg;
  },
  sendEmail_Registration: async function(lang, emailto, user, idapp, idreg) {

    // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      strlinksito: tools.getHostByIdApp(idapp),
      strlinkreg: this.getlinkReg(idapp, idreg),
      forgetpwd: tools.getHostByIdApp(idapp) + '/requestresetpwd',
      emailto: emailto,
      user,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

    this.sendEmail_base(tools.getpathregByIdApp(idapp, lang), emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));

    // Send to the Admin an Email
    this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');

    await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);

    if (tools.getConfSiteOptionEnabledByIdApp(mylocalsconf.idapp, shared_consts.ConfSite.Notif_Reg_Push_Admin)) {
      const nometot = tools.getNomeCognomeEUserNameByUser(mylocalsconf);

      let aportador = mylocalsconf.aportador_solidario ? ' (da ' + mylocalsconf.aportador_solidario + ')' : '';

      const numutenti = await User.getNumUsers(mylocalsconf.idapp);
      tools.sendNotifToAdmin(mylocalsconf.idapp, true, '++Reg [' + numutenti + '] ' + nometot + aportador);
    }

    // if (tools.isManagAndAdminDifferent(idapp)) {
    //   this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
    // }
  },
  sendEmail_IscrizioneConacreis: async function(lang, emailto, iscritto, idapp) {

    // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      strlinksito: tools.getHostByIdApp(idapp),
      emailto: emailto,
      iscritto,
      metodo_pagamento: tools.getPaymentTypesById(iscritto.metodo_pagamento),
      data_nascita: tools.getstrDate_DD_MM_YYYY(iscritto.dateofbirth),
    };

    mylocalsconf = this.setParamsForTemplate(iscritto, mylocalsconf);

    this.sendEmail_base('iscrizione_conacreis/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));

    // Send to the Admin an Email
    this.sendEmail_base('admin/iscrizione_conacreis/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');

    await telegrambot.notifyIscrizioneToTelegram(telegrambot.phase.ISCRIZIONE_CONACREIS, mylocalsconf, 'MSG_ISCRITTO_CONACREIS');

    tools.sendNotifToAdmin(idapp, true, 'Iscrizione Conacreis : ' + mylocalsconf.name + ' ' + mylocalsconf.surname + ' (' + mylocalsconf.username + ')');

    if (tools.isManagAndAdminDifferent(idapp)) {
      this.sendEmail_base('admin/iscrizione_conacreis/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
    }
  },

  sendEmail_IscrizioneArcadei: async function(lang, emailto, iscritto, idapp) {

    // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
    try {

      let mylocalsconf = {
        idapp,
        dataemail: await this.getdataemail(idapp),
        locale: lang,
        nomeapp: tools.getNomeAppByIdApp(idapp),
        strlinksito: tools.getHostByIdApp(idapp),
        emailto: emailto,
        iscritto,
        metodo_pagamento: tools.getPaymentTypesById(iscritto.metodo_pagamento),
        data_nascita: tools.getstrDate_DD_MM_YYYY(iscritto.dateofbirth),
      };

      mylocalsconf = this.setParamsForTemplate(iscritto, mylocalsconf);

      this.sendEmail_base('iscrizione_arcadei/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));

      // Send to the Admin an Email
      this.sendEmail_base('admin/iscrizione_arcadei/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');

      await telegrambot.notifyIscrizioneToTelegram(telegrambot.phase.ISCRIZIONE_ARCADEI, mylocalsconf, 'MSG_ISCRITTO_ARCADEI');

      tools.sendNotifToAdmin(idapp, true, 'Iscrizione Arcadei : ' + mylocalsconf.name + ' ' + mylocalsconf.surname + ' (' + mylocalsconf.username + ')');

      if (tools.isManagAndAdminDifferent(idapp)) {
        this.sendEmail_base('admin/iscrizione_arcadei/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
      }
    } catch (e) {
      console.error('Err', e);
    }
  },

  sendEmail_RequestNewPassword: async function(lang, user, emailto, idapp, tokenforgot, tokenforgot_code) {
    console.log('sendEmail_RequestNewPassword');

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      strlinksetpassword: tools.getlinkRequestNewPassword(idapp, emailto, tokenforgot),
      tokenforgot_code,
      emailto: emailto,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

    this.sendEmail_base('resetpwd/' + lang, emailto, mylocalsconf, '');
  },

  sendEmail_Booking: async function(res, lang, emailto, user, idapp, recbooking) {

    tools.mylog('sendEmail_Booking');
    tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      emailto: emailto,
      msgbooking: '',
      participants: '',
      participantsLunch: '',
      participantsDinner: '',
      participantsDinnerShared: '',
      msgbooking: tools.convertTexttoHtml(recbooking.msgbooking),
      eventtextplain: tools.removeSpecialCharForEmail(recbooking.infoevent),
      event: recbooking.infoevent,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

    return await Settings.getValDbSettings(idapp, 'MSG_REPLY_AFTER_BOOKING').then(async (ris) => {
      mylocalsconf.msgreply_after_booking = ris;

      mylocalsconf = await this.preparaConfPerBooking(res, idapp, mylocalsconf, recbooking, 'Prenotazione');

      if (recbooking.modified) {
        texthtml = 'modifybooking';
      } else {
        texthtml = 'makebooking';
      }

      this.sendEmail_base('booking/' + texthtml + '/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));

      // Send Email also to the Admin
      this.sendEmail_base('admin/' + texthtml + '/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');

      if (tools.isManagAndAdminDifferent(idapp)) {
        this.sendEmail_base('admin/' + texthtml + '/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
      }

    });

  },

  preparaConfPerBooking: async function(res, idapp, mylocalsconf, recbooking, title) {

    let texthtml = '';
    let msgtelegram = title + ' Evento [' + mylocalsconf.username + ' (' + mylocalsconf.name + ' ' + mylocalsconf.surname + ')] ' +
        mylocalsconf.eventtextplain;
    if (recbooking.modified) {
      msgtelegram += ' (modificato) ';
    } else {
      msgtelegram += ' (Nuovo)';
    }

    msgtelegram += '\n';

    if (recbooking.msgbooking) {
      mylocalsconf.msgbooking = 'Messaggio: ' + recbooking.msgbooking.toString()
      msgtelegram += mylocalsconf.msgbooking + '\n';
    }
    if (recbooking.numpeople > 0) {
      mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + tools.getres__('partecipanti', res);
      msgtelegram += mylocalsconf.participants + '\n';
    }

    if (recbooking.numpeopleLunch > 0) {
      mylocalsconf.participantsLunch = recbooking.numpeopleLunch.toString() + ' ' + tools.getres__('partecipanti a Pranzo', res);
      msgtelegram += mylocalsconf.participantsLunch + '\n';
    }

    if (recbooking.numpeopleDinner > 0) {
      mylocalsconf.participantsDinner = recbooking.numpeopleDinner.toString() + ' ' + tools.getres__('partecipanti a Cena', res);
      msgtelegram += mylocalsconf.participantsDinner + '\n';
    }

    if (recbooking.numpeopleDinnerShared > 0) {
      mylocalsconf.participantsDinnerShared = recbooking.numpeopleDinnerShared.toString() + ' ' +
          tools.getres__('partecipanti a Cena Condivisa', res);
      msgtelegram += mylocalsconf.participantsDinnerShared + '\n';
    }

    telegrambot.sendMsgTelegramToTheManagers(idapp, msgtelegram);

    return mylocalsconf;

  },

  getName: function(mylocalsconf) {
    return mylocalsconf.name ? (mylocalsconf.surname ? (mylocalsconf.name + ' ' + mylocalsconf.surname) : mylocalsconf.name) : mylocalsconf.username
  },

  sendEmail_CancelBooking: async function(res, lang, emailto, user, idapp, recbooking) {

    tools.mylog('sendEmail_CancelBooking');

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      event: recbooking.infoevent,
      participants: '',
      participantsLunch: '',
      participantsDinner: '',
      participantsDinnerShared: '',
      eventtextplain: tools.removeSpecialCharForEmail(recbooking.infoevent),
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

    mylocalsconf.emailto = emailto;

    mylocalsconf = await this.preparaConfPerBooking(res, idapp, mylocalsconf, recbooking, 'Cancellazione');

    let msgtelegram = 'Cancellazione Evento [' + this.getName(mylocalsconf) + '] ' + mylocalsconf.eventtextplain;

    telegrambot.sendMsgTelegramToTheManagers(idapp, msgtelegram);

    this.sendEmail_base('booking/cancelbooking/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));

    // Send Email also to the Admin
    this.sendEmail_base('admin/cancelbooking/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');

    if (tools.isManagAndAdminDifferent(idapp)) {
      this.sendEmail_base('admin/cancelbooking/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
    }
  },

  sendEmail_Msg: async function(res, lang, emailto, user, idapp, recmsg) {

    tools.mylog('sendEmail_Msg');
    tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);

    mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      usernameorig: user.name + ' ' + user.surname,
      message: tools.convertTexttoHtml(recmsg.message),
      infoevent: recmsg.source.infoevent,
      strlinkreply: tools.getHostByIdApp(idapp) + '/messages/' + recmsg._id,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);
    mylocalsconf.emailto = emailto;

    let replyto = '';
    if (mylocalsconf.infoevent !== '')
      replyto = user.email;
    else
      replyto = tools.getreplyToEmailByIdApp(idapp);

    return await this.sendEmail_base('msg/sendmsg/' + lang, emailto, mylocalsconf, replyto);

    // Send Email also to the Admin
    // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf);
  },

  sendEmail_ByText: async function(lang, emailto, user, idapp, rec) {

    tools.mylog('sendEmail_ByText');

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      usernameorig: user.name + ' ' + user.surname,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);
    mylocalsconf.emailto = emailto;

    mylocalsconf.dataemail.emailbody = rec.emailbody;
    mylocalsconf.dataemail.emailtitle = rec.emailtitle;

    if (!!mylocalsconf.dataemail.emailtitle && !!mylocalsconf.dataemail.emailbody) {
      const replyto = tools.getreplyToEmailByIdApp(idapp);

      //return this.sendEmail_base('standard', emailto, mylocalsconf, replyto);
      return await this.sendEmail_Normale(emailto, mylocalsconf.dataemail.emailtitle, mylocalsconf.dataemail.emailbody, replyto);
    }

    // Send Email also to the Admin
    // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf);
  },

  sendEmail_ByNotif: async function(lang, emailto, user, idapp, recnotif) {

    tools.mylog('sendEmail_ByNotif');

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      usernameorig: user.name + ' ' + user.surname,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);
    mylocalsconf.emailto = emailto;

    mylocalsconf.dataemail.emailtitle = recnotif.title;
    mylocalsconf.dataemail.emailbody = tools.getTextNotifByRecNotif(recnotif);

    if (!!mylocalsconf.dataemail.emailtitle && !!mylocalsconf.dataemail.emailbody) {
      const replyto = tools.getreplyToEmailByIdApp(idapp);

      //return this.sendEmail_base('standard', emailto, mylocalsconf, replyto);
      return await this.sendEmail_Normale(emailto, mylocalsconf.dataemail.emailtitle, mylocalsconf.dataemail.emailbody, replyto);
    }

    // Send Email also to the Admin
    // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf);
  },

  Add_to_MailingList_AndSendEmailNotify: async function(lang, user, idapp, sendnews) {

    // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));

    let mylocalsconf = {
      idapp,
      dataemail: await this.getdataemail(idapp),
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

    const hash = tools.getHash(mylocalsconf.emailto);

    // Check if exist to the Mailing List
    let myperson = await MailingList.findByHash(idapp, hash);
    if (!myperson || !myperson.statesub || !myperson.wrongerr) {
      if (!myperson) {
        myperson = new MailingList({
          name: mylocalsconf.name,
          surname: mylocalsconf.surname,
          email: mylocalsconf.emailto,
          hash,
        });
        myperson._id = new ObjectID();
      } else {
        myperson.name = mylocalsconf.name;
        myperson.surname = mylocalsconf.surname;
        //myperson.email = mylocalsconf.emailto;
        //myperson.hash = hash;
      }

      myperson.idapp = idapp;
      myperson.statesub = true; // subscription
      myperson.wrongerr = false;

      // Add/save new record to the DB MailingList
      const res = await myperson.save();

      if (sendnews) {
        // Send to the Admin an Email
        this.sendEmail_base('admin/added_to_newsletter/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');

        if (tools.isManagAndAdminDifferent(idapp)) {
          this.sendEmail_base('admin/added_to_newsletter/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
        }
      }

      return {code: server_constants.RIS_SUBSCRIBED_OK, msg: server_constants.RIS_SUBSCRIBED_MSG[lang]};
    } else {
      // Already Esist
      return {
        code: server_constants.RIS_SUBSCRIBED_ALREADYEXIST,
        msg: server_constants.RIS_SUBSCRIBED_MSG_ALREADYEXIST[lang],
      };
    }

  },

  Remove_from_MailingList: async function(lang, hashemail, idapp) {

    // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));

    // Check if exist to the Mailing List
    if (await MailingList.isUnsubscribed(idapp, hashemail)) {
      return {
        myperson: null,
        code: server_constants.RIS_UNSUBSCRIBED_ALREADY_DONE,
        msg: server_constants.RIS_UNSUBSCRIBED_MSG_ALREADY_DONE[lang],
      };
    }

    const fields_to_update = {
      statesub: false,
    };
    let myperson = await MailingList.findOneAndUpdate({
      idapp,
      hash: hashemail,
    }, {$set: fields_to_update}, {new: false});
    if (myperson) {
      return {myperson, code: server_constants.RIS_UNSUBSCRIBED_OK, msg: ''};

    } else {
      // Not found !
      return {
        myperson: null,
        code: server_constants.RIS_UNSUBSCRIBED_NOT_EXIST,
        msg: server_constants.RIS_UNSUBSTR_NOT_EXIST[lang],
      };
    }

  },

  fieldsloop: function(mylocalsconf, myvar) {
    const baseurl = tools.getHostByIdApp(mylocalsconf.idapp);
    const urlunsibscribe = baseurl + '/unsubscribe?em=' + mylocalsconf.hashemail + '&mc=' + mylocalsconf.dataemail.mailchimpactive +
        '&email=' + mylocalsconf.emailto;

    let out = myvar.replace('{urlunsubscribe}', urlunsibscribe);
    out = out.replace('{email}', mylocalsconf.emailto);
    out = out.replace('{username}', mylocalsconf.username);
    out = out.replace('{name}', mylocalsconf.name ? mylocalsconf.name : mylocalsconf.username);
    out = out.replace('{surname}', mylocalsconf.surname ? mylocalsconf.surname : '');
    out = out.replace('{aportador_solidario}', mylocalsconf.aportador_solidario ? mylocalsconf.aportador_solidario : '');

    return out;
  },

  replacefields: function(mylocalsconf) {
    try {
      mylocalsconf.dataemail.disclaimer_out = !!mylocalsconf.dataemail.disclaimer ? this.fieldsloop(mylocalsconf,
          mylocalsconf.dataemail.disclaimer) : '';
      mylocalsconf.dataemail.disc_bottom_out = !!mylocalsconf.dataemail.disc_bottom ? this.fieldsloop(mylocalsconf,
          mylocalsconf.dataemail.disc_bottom) : '';
      if (mylocalsconf.dataemail.templ)
        mylocalsconf.dataemail.templ.testoheadermail_out = !!mylocalsconf.dataemail.templ.testoheadermail ? this.fieldsloop(mylocalsconf,
            mylocalsconf.dataemail.templ.testoheadermail) : '';
    } catch (e) {
      console.error('Error replacefields: ' + e);
    }

    return mylocalsconf;
  },

  getdataemail: async (idapp) => {
    // console.log('getdataemail');
    const mydata = {
      content_after_events: await Settings.getValDbSettings(idapp, 'TEXT_AFTER_EV'),
      mailchimpactive: tools.BoolToInt(await Settings.getValDbSettings(idapp, 'MAILCHIMP_ON')),
      urltwitter: await Settings.getValDbSettings(idapp, 'URL_TWITTER'),
      urlfb: await Settings.getValDbSettings(idapp, 'URL_FACEBOOK'),
      urlyoutube: await Settings.getValDbSettings(idapp, 'URL_YOUTUBE'),
      urlinstagram: await Settings.getValDbSettings(idapp, 'URL_INSTAGRAM'),
      textpromo: await Settings.getValDbSettings(idapp, 'TEXT_PROMO'),
      disclaimer: await Settings.getValDbSettings(idapp, 'TEXT_DISCLAIMER'),
      disc_bottom: await Settings.getValDbSettings(idapp, 'TEXT_DISC_BOTTOM'),
      firma: await Settings.getValDbSettings(idapp, 'TEXT_SIGN'),

      arrdiscipline: await Discipline.getDisciplineforNewsletter(idapp),
      disc_title: await Settings.getValDbSettings(idapp, 'DISC_TITLE'),
      height_logo: await Settings.getValDbSettings(idapp, 'HEIGHT_LOGO'),
      from: await Settings.getValDbSettings(idapp, 'EMAIL_FROM'),
      email_reply: await Settings.getValDbSettings(idapp, 'EMAIL_REPLY', ''),
      pwd_from: await Settings.getValDbSettings(idapp, 'PWD_FROM'),
      email_service: await Settings.getValDbSettings(idapp, 'EMAIL_SERVICE_SEND'),
      email_port: await Settings.getValDbSettings(idapp, 'EMAIL_PORT'),
      templemail_id: await Settings.getValDbSettings(idapp, 'TEMPLEMAIL_ID'),
    };

    // console.log(mydata.templemail_id);
    mydata.templ = await TemplEmail.findOne({_id: mydata.templemail_id});
    // console.log(mydata.templ);

    return mydata;
  },

  getTransport: (mylocalsconf) => {
    // Create Transport
    let smtpTransport = null;

    // console.log('mylocalsconf.dataemail', mylocalsconf.dataemail);

    if (mylocalsconf.dataemail.email_service !== 'gmail' && mylocalsconf.dataemail.email_service !== undefined &&
        mylocalsconf.dataemail.email_service !== '') {
      smtpTransport = nodemailer.createTransport({
        host: mylocalsconf.dataemail.email_service,
        port: mylocalsconf.dataemail.email_port,
        secureConnection: true,
        tls: {cipher: 'SSLv3'},
        auth: {
          user: mylocalsconf.dataemail.from,
          pass: tools.decryptdata(mylocalsconf.dataemail.pwd_from),
        },
      });
    } else if (mylocalsconf.dataemail.email_service === 'gmail' && !!mylocalsconf.dataemail.pwd_from) {

      //smtpTransport = {
      smtpTransport = nodemailer.createTransport({
        service: 'gmail', //'Gmail',
        auth: {
          user: mylocalsconf.dataemail.from,
          pass: tools.decryptdata(mylocalsconf.dataemail.pwd_from),
        },
      });
    } else {
      // smtpTransport = {
      smtpTransport = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: tools.getEmailByIdApp(mylocalsconf.idapp),
          pass: tools.getPwdByIdApp(mylocalsconf.idapp),
        },
      });
    }

    // console.log('smtpTransport', smtpTransport);

    return smtpTransport;
  },

  setParamsForTemplate: function(user, mylocalsconf) {

    try {
      mylocalsconf.username = user.username;
      mylocalsconf.name = user.name;
      mylocalsconf.surname = user.surname;
      mylocalsconf.aportador_solidario = user.aportador_solidario ? user.aportador_solidario : '';
      mylocalsconf.emailto = user.email;
      mylocalsconf.hashemail = tools.getHash(user.email);
      mylocalsconf.user = user;

      mylocalsconf = this.replacefields(mylocalsconf);
    } catch (e) {
      console.error('setParamsForTemplate', e);
    }

    return mylocalsconf;
  },

  sendEmail_OrderProduct: async function(lang, idapp, orders, user) {

    const msginizio = 'Ordine n: ' + orders.numorder + ' ' + user.name + ' ' + user.surname;
    console.log(msginizio);

    await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio);

    let mylocalsconf = {
      idapp,
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      orders,
      baseurl: tools.getHostByIdApp(idapp),
      dataemail: await this.getdataemail(idapp),
      ordernumber: orders.numorder,
      user,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

    this.sendEmail_base_e_manager(idapp, 'ecommerce/makeorder/' + lang, mylocalsconf.emailto, mylocalsconf,
        mylocalsconf.dataemail.email_reply);

  },
  sendEmail_Order: async function(lang, idapp, orders, user, ordertype, status) {

    const msginizio = 'INIZIO - sendEmail_Order ' + ordertype + ': ' + tools.getNomeAppByIdApp(idapp);
    console.log(msginizio);

    await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio);

    let mylocalsconf = {
      idapp,
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      orders,
      baseurl: tools.getHostByIdApp(idapp),
      dataemail: await this.getdataemail(idapp),
      ordernumber: orders.numorder,
      user,
    };

    mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

    if ((status !== shared_consts.OrderStatus.CANCELED) && (status !== shared_consts.OrderStatus.RECEIVED)) {
      const esito = this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, mylocalsconf.emailto, mylocalsconf,
          mylocalsconf.dataemail.email_reply);

      this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');

      if (tools.isManagAndAdminDifferent(idapp)) {
        this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
      }
    }

  },

  sendEmail_Newsletter_Events: async function(lang, idapp, id_newstosent) {

    const msginizio = 'INIZIO - sendEmail_Newsletter_Events: ' + tools.getNomeAppByIdApp(idapp);
    console.log(msginizio);

    await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio);

    //++Todo Extract List Email to send
    const userstosend = await MailingList.findAllIdAppSubscribed(idapp);

    const myarrevents = await MyEvent.getLastEvents(idapp);

    let mylocalsconf = {
      idapp,
      locale: lang,
      nomeapp: tools.getNomeAppByIdApp(idapp),
      arrevents: myarrevents,
      baseurl: tools.getHostByIdApp(idapp),
      dataemail: await this.getdataemail(idapp),
    };

    await Newstosent.processingJob(id_newstosent, true);

    const mynewsrec = await Newstosent.findOne({_id: id_newstosent});

    try {
      mynewsrec.numemail_tot = userstosend.length;
      mynewsrec.templemail_str = mylocalsconf.dataemail.templ.subject;
      mynewsrec.numemail_sent = await MailingList.getnumSent(idapp, id_newstosent);

      const smtpTransport = this.getTransport(mylocalsconf);

      // LOOP USERS EMAIL
      for (const user of userstosend) {

        try {

          const isok = await MailingList.isOk(idapp, user._id, id_newstosent);
          if (isok) {
            let secpause = await Settings.getValDbSettings(idapp, 'MSEC_PAUSE_SEND', process.env.DELAY_SENDEMAIL);
            if (secpause < process.env.DELAY_SENDEMAIL)
              secpause = process.env.DELAY_SENDEMAIL;

            const activate = await Newstosent.isActivated(id_newstosent);

            if (!activate) {
              // Invio Newsletter Abortito!
              mynewsrec.error_job = 'Invio Newsletter abortito alle ore ' + new Date().toDateString() + new Date().toTimeString();
              await telegrambot.sendMsgTelegramToTheManagers(idapp, mynewsrec.error_job);
              await mynewsrec.save();
              await Newstosent.processingJob(id_newstosent, false);
              console.log('*** L\'Invio della Newsletter è stato fermato ! ');
              return false;
            }

            mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);

            // If has already sent, don't send it again!
            if (user.lastid_newstosent !== id_newstosent.toString()) {
              // console.log('@@@@@ COMPARE DIVERSI: lastid', user.lastid_newstosent, 'idsent', id_newstosent.toString());

              if (process.env.DEBUG)
                await tools.snooze(5000);

              // Send Email to the User
              // console.log('-> Invio Email (', mynewsrec.numemail_sent, '/', mynewsrec.numemail_tot, ')');
              const esito = this.sendEmail_base('newsletter/' + lang, mylocalsconf.emailto, mylocalsconf,
                  mylocalsconf.dataemail.email_reply, smtpTransport);

              if ((mynewsrec.numemail_sent % 100) === 0) {
                const msgproc = 'In Corso ' + mynewsrec.numemail_sent + ' / ' + mynewsrec.numemail_tot + ' Email inviate...';
                await telegrambot.sendMsgTelegramToTheManagers(idapp, msgproc);
              }

              //Put the result in the database, to check if is sent or not.
              const updateml = await MailingList.findOneAndUpdate({
                idapp,
                email: user.email,
              }, {$set: {lastid_newstosent: ObjectID(id_newstosent)}}, {new: false});

              //Delay for send email...
              await tools.snooze(secpause);

              mynewsrec.lastemailsent_Job = new Date();
              mynewsrec.numemail_sent = await MailingList.getnumSent(idapp, id_newstosent);

              const recsaved = await mynewsrec.save();
            } else {
              console.log('*** COMPARE: UGUALI !!!!! lastid', user.lastid_newstosent, 'idsent', id_newstosent.toString());
            }
          }
        } catch (e) {
          const msgerr = 'Error LOOP sendEmail_Newsletter_Events: ' + e;
          console.error(msgerr);
          await telegrambot.sendMsgTelegramToTheManagers(idapp, msgerr);
        }
      }

      await Newstosent.endJob(id_newstosent);
      await Newstosent.processingJob(id_newstosent, false);
      let msgfine = 'FINE - sendEmail_Newsletter_Events [' + tools.getNomeAppByIdApp(idapp) + ']: ';
      msgfine += mynewsrec.numemail_sent + ' Email inviate';
      console.log(msgfine);

      await telegrambot.sendMsgTelegramToTheManagers(idapp, msgfine);

    } catch (e) {

      const activate = await Newstosent.isActivated(id_newstosent);

      if (!activate) {
        // Invio Newsletter Abortito!
        mynewsrec.error_job = 'Invio Newsletter abortito alle ore ' + new Date().toDateString() + new Date().toTimeString();
        await telegrambot.sendMsgTelegramToTheManagers(idapp, mynewsrec.error_job);
        await mynewsrec.save();
        await Newstosent.processingJob(id_newstosent, false);
        console.log('*** L\'Invio della Newsletter è stato fermato ! ');
        return false;
      }
    }

  },

  checkifSentNewsletter: async function(idapp) {
    // Check if is the time to send the Newsletter

    return await Newstosent.findNewsletter_To_Send(idapp).then((rec) => {
      if (rec)
        this.sendNewsletter(rec);
    });
  }
  ,

  checkifPendingNewsletter: async function(idapp) {
    // Check if is the time to send the Newsletter
    // Only newsletter pending en 8 hour last email sent.

    return await Newstosent.findNewsletterPending_To_Send(idapp).then((rec) => {  //
      this.sendNewsletter(rec, idapp);
    });
  },

  sendNewsletter: async function(rec, idapp) {
    if (rec) {
      // Start the job
      let myjobnews = await Newstosent.findOne({_id: rec._id});
      if (!!myjobnews) {
        myjobnews.starting_job = true;
        myjobnews.datestartJob = new Date();

        myjobnews.save().then((ris) => {

          this.sendEmail_Newsletter_Events('it', idapp, rec._id);
        }).catch((e) => {
          console.error(e.message);
        });
      }
    }
  },

  testemail: async function(idapp, lang, previewonly) {

    const myarrevents = await MyEvent.getLastEvents(idapp);
    const myemail = await Settings.getValDbSettings(idapp, 'EMAIL_TEST');
    if (myemail) {
      let mylocalsconf = {
        idapp,
        locale: lang,
        nomeapp: tools.getNomeAppByIdApp(idapp),
        arrevents: myarrevents,
        name: 'TestNome',
        surname: 'TestCognome',
        subject: '',
        emailto: myemail,
        baseurl: tools.getHostByIdApp(idapp),
        hashemail: tools.getHash(myemail),
      };

      console.log('myarrevents');
      console.table(mylocalsconf.arrevents);

      mylocalsconf.dataemail = await this.getdataemail(idapp);

      this.replacefields(mylocalsconf);

      const smtpTransport = this.getTransport(mylocalsconf);

      console.log('-> Invio Email TEST a', mylocalsconf.emailto, 'previewonly',
          previewonly);
      return await this.sendEmail_base('newsletter/' + lang, mylocalsconf.emailto,
          mylocalsconf, '', smtpTransport, previewonly);
    }

  },

  testemailHtml: async function(idapp, lang, email, myuser) {

    let mytitle = 'Prova msg';
    let messaggio = '<br><b>Ciao!</b><div>Come stai?</div><br>Tutto Bene?<br><a href="https://ayni.gifteconomy.app/">Prova Link</a><br><i>Corsivo</i></i>&nbsp;';

    /*const htmlToText = require('html-to-text');

    messaggio = htmlToText.fromString(messaggio, {
      wordwrap: 80,
      preserveNewlines: true,
      singleNewLineParagraphs: true
    });
    */

    return await this.sendEmail_ByText(lang, email, myuser, idapp, {
      emailbody: messaggio,
      emailtitle: mytitle,
    });

  },

}
;
