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

const express = require('express');
const router = express.Router();
const request = require('superagent');

const sendemail = require('../sendemail');

const { User } = require('../models/user');
const { MailingList } = require('../models/mailinglist');
const { Newstosent } = require('../models/newstosent');
const { TemplEmail } = require('../models/templemail');
const { OpzEmail } = require('../models/opzemail');
const { Settings } = require('../models/settings');

const tools = require('../tools/general');
const { authenticate } = require('../middleware/authenticate');

const newsletter = [
  {
    name: 'Paolo',
    mailchimpInstance: 'us16',
    listUniqueId: 'e70fd8ba4c',
    mailchimpApiKey: '24d1eb0e4f21dd7c52d47214b0d62cfd-us16'
    // CLIENT ID 682712991042
    // Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
  },
  {
    name: 'Paolo',
    mailchimpInstance: 'us16',
    listUniqueId: 'e70fd8ba4c',
    mailchimpApiKey: '24d1eb0e4f21dd7c52d47214b0d62cfd-us16'
    // CLIENT ID 682712991042
    // Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
  },
  {
    name: 'AssShen',
    mailchimpInstance: 'us4',
    listUniqueId: '991c0b8321',
    mailchimpApiKey: '07dd8b0bd078ae3a79e398656c276bbd-us4'
    // CLIENT ID 682712991042
    // Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
  },
  {
    name: 'AssociazioneShen',
    mailchimpInstance: '',
    listUniqueId: '',
    mailchimpApiKey: ''
  },
];

async function AddMailingList(locale, idapp, user, settomailchimp, sendnews) {

  return await sendemail.Add_to_MailingList_AndSendEmailNotify(locale, user, idapp, sendnews).then((ris) => {

    if (settomailchimp) {
      request
        .post('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/')
        .set('Content-Type', 'application/json;charset=utf-8')
        .set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64'))
        .send({
          'email_address': req.body.email,
          'status': server_constants.RIS_SUBSCRIBED_STR,
          'merge_fields': {
            'FNAME': user.name,
            'LNAME': user.surname
          }
        })
        .end(function (err, response) {
          console.log("STAT", response.status);

          if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
            if (response.status === 400 && response.body.title === "Member Exists")
              return {
                code: server_constants.RIS_SUBSCRIBED_ALREADYEXIST,
                msg: server_constants.RIS_SUBSCRIBED_MSG_ALREADYEXIST[locale]
              };
            else
              return {
                code: server_constants.RIS_SUBSCRIBED_OK,
                msg: server_constants.RIS_SUBSCRIBED_MSG[locale]
              };
          } else {
            return {
              code: server_constants.RIS_SUBSCRIBED_ERR,
              msg: server_constants.RIS_SUBSCRIBED_MSG_FAILED[locale]
            };
          }
        });

    } else {
      return ris;
    }

  });
}

router.post('/signup', (req, res) => {

  settomailchimp = req.body.settomailchimp;
  idapp = req.body.idapp;
  locale = req.body.locale;

  const user = {
    email: req.body.email,
    name: req.body.firstName,
    surname: req.body.lastName,
  };

  return AddMailingList(locale, idapp, user, settomailchimp, true).then((ris) => {
    return res.send(ris);
  });

});

async function ImportData(locale, idapp, strdata, settomailchimp) {

  try {
    let numadded = 0;
    let numtot = 0;
    let numalreadyexisted = 0;

    // Convert to array
    let arrusers = strdata.split('\n');
    if (arrusers.length <= 0)
      arrusers = strdata.split(',');
    if (arrusers.length <= 0)
      arrusers = strdata.split(';');
    if (arrusers.length <= 0)
      arrusers = strdata.split('\t');

    let sep = '';

    // Controlla se ci sono spazi
    const arrtab = arrusers[0].split('\t');
    const arrspace = arrusers[0].split(' ');
    const arrcomma = arrusers[0].split(',');
    if (arrtab.length > 1) {
      sep = '\t';
    }
    if (arrspace.length > 1) {
      sep = ' '
    }
    if (arrcomma.length > 1) {
      sep = ','
    }

    console.log('arrtab', arrtab);
    console.log('arrspace', arrspace);
    console.log('arrcomma', arrcomma);

    console.log('sep', sep);


    try {
      for (const row of arrusers) {
        if (sep !== '') {
          let arrrow = row.split(sep);
          if (arrrow.length === 1) {
            user = {
              name: '',
              surname: '',
              email: arrrow[0]
            }
          } else {
            user = {
              name: arrrow[0],
              surname: arrrow[1],
              email: arrrow[2],
            }
          }
        } else {
          user = {
            name: '',
            surname: '',
            email: row
          }
        }
        console.log('user', user);
        if (user.email.indexOf('@') > -1) {
          numtot++;

          await AddMailingList(locale, idapp, user, settomailchimp, false).then((ris) => {
            console.log('Addmail user', user, 'ris', ris);
            if (ris.code === server_constants.RIS_SUBSCRIBED_OK)
              numadded++;
            else if (ris.code === server_constants.RIS_SUBSCRIBED_ALREADYEXIST)
              numalreadyexisted++;
          });
        }
      }

    } catch (e) {

    }

    ris = { numadded, numtot, numalreadyexisted };

    console.log(ris);
    return ris

  } catch (e) {
    console.err(e.message);
  }
}

router.post('/import', async (req, res) => {

  settomailchimp = req.body.settomailchimp;
  const strdata = req.body.strdataemail;
  idapp = req.body.idapp;
  locale = req.body.locale;

  const ris = await ImportData(locale, idapp, strdata, settomailchimp);
  console.log('ris', ris);

  res.send(ris);
});

async function getDataNewsletter(lang, idapp) {
  const arrml = await MailingList.findAllIdApp(idapp);

  const lastnewstosent = await Newstosent.getlast(idapp);
  const nextnewstosent = await Newstosent.findNewsletter_To_Send(idapp);
  const lastid = (lastnewstosent) ? lastnewstosent._id : 0;

  const data = {
    lastnewstosent,
    nextnewstosent,
    totemail: 0,
    totsubscribed: 0,
    totunsubscribed: 0,
    totsentlastid: 0,
  };

  for (const user of arrml) {
    data.totemail++;
    if (user.statesub)
      data.totsubscribed++;
    else
      data.totunsubscribed++;
    if (user.lastid_newstosent === lastid) {
      data.totsentlastid++;
    }
  }

  // await tools.snooze(2000);

  return data;
}

router.post('/load', authenticate, async (req, res) => {

  idapp = req.body.idapp;
  locale = req.body.locale;

  const ris = {
    newsstate: await getDataNewsletter(locale, idapp),
    serv_settings: await Settings.findAllIdApp(idapp, true, false),
    templemail: await TemplEmail.findAllIdApp(idapp, true),
    opzemail: await OpzEmail.findAllIdApp(idapp)
  };

  return res.send(ris);
});

router.post('/setactivate', authenticate, async (req, res) => {

  idapp = req.body.idapp;
  activate = req.body.activate;
  id = req.body._id;
  locale = req.body.locale;

  const rec = {
    activate,
  };

  return await Newstosent.findOneAndUpdate({ _id: id }, { $set: rec }, { new: false }).then((item) => {
    const ris = getDataNewsletter(locale, idapp);

    return res.send(ris);

  });

});

router.post('/unsubscribe', (req, res) => {

  console.log('unsubscribe -> ', req.body);

  hashemail = req.body.em;
  mailchimpactive = tools.StrToBool(req.body.mc);
  idapp = req.body.idapp;
  locale = req.body.locale;

  sendemail.Remove_from_MailingList(locale, hashemail, idapp).then((ris) => {
    console.log('Remove_from_MailingList -> ', ris);

    if (!!ris.myperson && mailchimpactive) {
      const subscriber_md5_email = tools.getmd5(ris.myperson.email);
      request
        .put('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/' + subscriber_md5_email)
        .set('Content-Type', 'application/json;charset=utf-8')
        .set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64'))
        .send({
          'email_address': ris.myperson.email,
          'status': server_constants.RIS_UNSUBSCRIBED_STR
        })
        .end(function (err, response) {
          console.log("STAT", response.status);

          if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
            res.send({
              code: server_constants.RIS_UNSUBSCRIBED_OK
            });
          } else {
            res.send({
              code: server_constants.RIS_SUBSCRIBED_ERR
            });
          }
        });

    } else {
      res.send({ code: ris.code, msg: ris.msg });
    }

  });

});


router.post('/testemail', authenticate, async (req, res) => {

  if (!User.isAdmin(req.user.perm)) {
    // If without permissions, exit
    return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
  }

  idapp = req.body.idapp;
  lang = req.body.locale;
  previewonly = req.body.previewonly;

  const test = false;

  let ris = null;

  if (test) {
    const email = 'pao.loarena77@gmail.com';
    const myuser = await User.findOne({ idapp, email });

    ris = await sendemail.testemailHtml(idapp, lang, email, myuser);
  } else {
    ris = await sendemail.testemail(idapp, lang, previewonly);
  }

  if (ris)
    return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
  else
    return res.send({ code: server_constants.RIS_CODE_EMAIL_NOT_SENT, msg: '' });

});

module.exports = router;
