"use strict";

const lodash = require("lodash");
const moment = require("moment");
const QRHelper = require("../../helpers/qr.helper");
const emailHelper = require("../../helpers/mail.helper");

////////////////////////////////////////////////////////////////////
// dataInscription {incription:{...}, {..., event:{...}, reservation:{...}, user:{...}}
////////////////////////////////////////////////////////////////////
/*AHORA SE ALMACENA TODO EN UNA ÚNICA LISTA DE MAILCHIMP, QUE ES LA DEL EVENTO 
(si en un futuro se quiere tener listas independientes, bastaría con tratarlo aqui los campos de marketinglist de la reserva ...)
      if (dataInscription.inscription.reservationId)
          marketingListOfInscription = dataInscription.reservation.marketingList
      else if (dataInscription.inscription.overflowEventId)
          marketingListOfInscription = (await _getEvent(dataInscription.inscription.overflowEventId)).marketingList;
      else 
          marketingListOfInscription = dataInscription.event.marketingList;
*/
function _generateMailDTO(dataInscription) {
  let inscriptionDTO = {};
//  console.log("*******ENTRO****", dataInscription);
  const inscription = dataInscription.inscription ? dataInscription.inscription : dataInscription;
  const event = dataInscription.event ? dataInscription.event : dataInscription.inscription.event;
  const reservation = dataInscription.reservation ? dataInscription.reservation : null;
  const user = dataInscription.user ? dataInscription.user : dataInscription.inscription.user;

  if (inscription) {
    inscriptionDTO.id = inscription.id;
    inscriptionDTO.source = inscription.source;
    inscriptionDTO.event_name = event ? event.name : "N/A";
    inscriptionDTO.event_venue = event && event.venue ? event.venue.name : null;
    inscriptionDTO.event_date = event ? event.init_date : "N/A";
    inscriptionDTO.event_marketing_list = event ? event.marketing_list : null;
    inscriptionDTO.date_inscription = inscription.date;
    inscriptionDTO.code_ticket = inscription.code_ticket;
    inscriptionDTO.validated = inscription.validated;
    inscriptionDTO.type = inscription.type; //   inscription.tipoEntrada ? inscription.tipoEntrada : inscription.type;

    inscriptionDTO.reservation_code = reservation ? reservation.reservation_code : null;
    inscriptionDTO.color = reservation ? reservation.color : null;
    inscriptionDTO.description =
      (reservation ? reservation.description : "Entrada").toUpperCase() +
      (lodash.words(inscription.type).includes("online") ? " online" : "");
    inscriptionDTO.qrConfig = null;
    inscriptionDTO.qrCode = null;

    if (user) {
      //Era para mailchimp
      ///        inscriptionDTO.marketing_memberId = inscription.marketing_memberId ? inscription.marketing_memberId : null;
      inscriptionDTO.email = user.email;
      inscriptionDTO.name = user.name;
      inscriptionDTO.surname = user.surname;
      inscriptionDTO.userId = user.id;
      inscriptionDTO.entity =
        reservation && reservation.Entity ? reservation.Entity.name : user.Entity ? user.Entity.name : user.entityId;
    }
  }
  //console.log("*******SALGO****", inscriptionDTO);
  return inscriptionDTO;
}

function generateHeaderMail(member) {
  let headerMail = null;
  let AsuntoOnline = lodash.words(member.type).includes("online") ? "Inscripción online" : "";
  let AsuntoOnsite = member.validated
    ? "Entrada"
    : lodash.words(member.type).includes("group")
    ? "Pendiente de confirmación"
    : "Lista de espera";

  if (member) {
    headerMail = {
      to: member.email,
      name: member.name + " " + member.surname,
      subject:
        (AsuntoOnline === "" ? AsuntoOnsite : AsuntoOnline) + " para evento " + member.event_name + " confirmada",
    };
  }

  return headerMail;
}

function generateHeaderMailReservation(reservation) {
  function _getDestinationMail() {
    if (lodash.isNull(reservation.Entity)) {
      return reservation.contact_email;
    } else {
      return reservation.Entity.contact_email ? reservation.Entity.contact_email : reservation.contact_email;
    }
  }

  let headerMail = null;

  if (reservation) {
    let toMail = _getDestinationMail();
    if (!lodash.isNull(toMail)) {
      headerMail = {
        to: toMail,
        name: reservation.Entity ? reservation.Entity.name : reservation.contact_name,
        bcc: "cbarrantes@loquedeverdadimporta.org",
        bccName: "Carolina Barrantes",
        subject: "Códigos de invitación para evento LQDVI",
      };
    }
  }
  console.log("generateHeaderMailReservation>>>>>>>", headerMail);
  return headerMail;
}

function generateBodyMailReservation(reservation) {
  console.log("generateBodyMailReservation>>>>>>>", reservation);
  const event = reservation.Event ? reservation.Event : reservation.event;
  let bodyMail = null;
  if (reservation) {
    bodyMail = {
      entityName: reservation.Entity ? reservation.Entity.name : reservation.contact_name,
      eventName: event.name,
      dateEvent: moment(event.init_date).format("D [de] MMMM [de] YYYY"),
      reservationCode: reservation.reservation_code,
      reservationDescription: reservation.description,
    };
  }
  console.log("generateBodyMailReservation>>>>>>>", bodyMail);
  return bodyMail;
}

function generateBodyMail(member) {
//  console.log('>>>generateBodyMail>>>>> ', member);
  let bodyMail = null;
  let tipoEntrada = lodash.words(member.type).includes("online")
    ? "Inscripción online confirmada"
    : member.validated
    ? "Entrada confirmada"
    : "Lista de espera";

  if (member) {
    bodyMail = {
      tipoEntrada: tipoEntrada,
      descriptionEntrada: member.description,
      qrCode: member.qrCode,
      qrCodeUrl: member.qrCodeUrl,
      color: member.qrConfig.color,
      codeTicket: member.code_ticket,
      idTicket: String(member.id_ticket? member.id_ticket : member.id),
      eventName: member.event_name,
      venueName: member.venue_name,
      dateEvent: moment(member.event_date).format("D [de] MMMM [de] YYYY, [a las] HH:mm"),
      dateInscription: moment(member.date_inscription).format("DD/MM/YY HH:mm "),
    };
  }
//  console.log('>>>retunr>>>>> ', bodyMail);
  return bodyMail;
}

async function sendEmailConfirm(dataUser, dataInscription) {

  dataInscription.user = dataUser.userResult.user;
  const isOnline = lodash.words(dataInscription.type).includes("online");
  let mailDTO = _generateMailDTO(dataInscription);

  mailDTO.qrConfig = QRHelper.generateQRConfig(mailDTO);
  mailDTO.qrCode = await QRHelper.getInscriptionQRCode(mailDTO.qrConfig);
  mailDTO.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);

  console.log("Mandamos mail con entrada , mailDTO>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  console.log(mailDTO);

  try {
    if (isOnline) emailHelper.sendTicketOnline(generateHeaderMail(mailDTO), generateBodyMail(mailDTO));
    else if (dataInscription.inscription.validated)
      emailHelper.sendTicket(generateHeaderMail(mailDTO), generateBodyMail(mailDTO));
    else {
      if (lodash.words(mailDTO.type).includes("group"))
        emailHelper.sendPendienteConfirmacion(generateHeaderMail(mailDTO), generateBodyMail(mailDTO));
      else emailHelper.sendListaEspera(generateHeaderMail(mailDTO), generateBodyMail(mailDTO));
    }
  } catch (error) {
    console.log("No se ha podido mandar email con entrada>>> ", error);
  }

  return true;
}

async function sendEmailCancelate(inscription) {
  let mailDTO = _generateMailDTO(inscription);

  mailDTO.qrConfig = QRHelper.generateQRConfig(mailDTO);
  mailDTO.qrCode = await QRHelper.getInscriptionQRCode(mailDTO.qrConfig);
  mailDTO.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
  let headerMail = generateHeaderMail(mailDTO);
  headerMail.subject = "Cancelación de " + headerMail.subject;

  console.log("Mandamos mail con la cancelacion>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  try {
    emailHelper.sendCancelacion(headerMail, generateBodyMail(mailDTO));
  } catch (error) {
    console.log("No se ha podido mandar email con cancelación");
  }

  return true;
}

/*async function _sendInscriptionEmail(dataInscription, member) {
  let mailDTO = _generateMailDTO(inscription);
  member.qrConfig = QRHelper.generateQRConfig(member);
  member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
  member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);

  console.log("Mandamos mail con entrada>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  //console.log(headerMail, bodyMail);

  try {
    if (member.validated) emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member));
    else emailHelper.sendListaEspera(generateHeaderMail(member), generateBodyMail(member));
  } catch (error) {
    console.log("No se ha podido mandar email con entrada");
  }
}*/

async function sendReservationEmail(reservation) {
  try {
    emailHelper.sendReservationCode(
      generateHeaderMailReservation(reservation),
      generateBodyMailReservation(reservation)
    );
  } catch (error) {
    console.log("No se ha podido mandar email _sendReservationEmail", error);
  }
}

async function sendReservationCollegeEmail(reservation) {
  try {
    emailHelper.sendReservationCodeCollege(
      generateHeaderMailReservation(reservation),
      generateBodyMailReservation(reservation)
    );
  } catch (error) {
    console.log("No se ha podido mandar email _sendReservationCodeCollege", error);
  }
}

module.exports = {
  sendEmailConfirm,
  sendEmailCancelate,
  sendReservationEmail,
  sendReservationCollegeEmail,
  generateHeaderMail,
  generateHeaderMailReservation,
  generateBodyMail,
  generateBodyMailReservation,
};
