"use strict";

const eventInscriptionService = require("./events_inscriptions.service");
const marketingHubspot = require("../../helpers/hubspot.helper"); // <--- HUBSPOT
const marketingSendinBlue = require("../../helpers/sendinblue.helper"); //<--- SendInBlue

////////////////////////////////////////////////////////////////////
// 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 _generateMarketingDTO(dataInscription) {
  console.log("entro _generateMarketingDTO >>> ", dataInscription);

  let { event, inscription, user, reservation } = dataInscription;
  let inscriptionDTO = {};

  //En el caso de generar el MarketingDTO para el ticket de la APP, fallaba porque el propio dataInscription, es la inscription y de el cuelgan user, event y reservation
  //Sin embargo cuando se llama desde addMarketingList la inscription cualga de dataInscripcion como el resto de elementos
  if (dataInscription) if (!inscription) inscription = dataInscription;

  if (!event) {
    throw new Error("Falta datos del evento en la inscripción (_generateMarketingDTO)");
  }

  /*if (!event.marketing_list) { <-- YA NO HACE FALTA CON HUBSPOT
    console.warn("Falta rellenar la lista de Sendinblue en el evento (_generateMarketingDTO)", event.name);
  }*/

  if (inscription) {
    inscriptionDTO.id = inscription.id;
    inscriptionDTO.source = inscription.source;
    inscriptionDTO.event_name = event.name ? event.name : "N/A";
    inscriptionDTO.event_date = event.init_date ? event.init_date : "N/A";
    inscriptionDTO.event_marketing_list = event ? event.marketing_list : null;
    inscriptionDTO.event_country = event ? event.location.country : null;
    inscriptionDTO.event_city = event ? event.location.city : null;
    inscriptionDTO.date_inscription = inscription.date;
    inscriptionDTO.code_ticket = inscription.code_ticket;
    inscriptionDTO.validated = inscription.validated;

    inscriptionDTO.reservation_code = reservation ? reservation.reservation_code : null;
    inscriptionDTO.color = reservation ? reservation.color : "darkgreen";
    inscriptionDTO.description = (reservation ? reservation.description : "Entrada").toUpperCase();
    inscriptionDTO.qrConfig = null;
    inscriptionDTO.qrCode = null;

    /** HUBSPOT */
    // inscriptionDTO.event_city = event.venue ? event.venue.city : null;
    // inscriptionDTO.event_country = event.venue ? event.venue.country : 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.phone = user.phone; // <-- HUBSPOT
      inscriptionDTO.profile = user.profile; // <-- HUBSPOT
      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 sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

async function _addMember(inscriptionDTO) {
  console.debug(">>>> _addMember", inscriptionDTO.email);
  console.debug(">>>> event_marketing_list", inscriptionDTO.event_marketing_list);
  //        console.debug(member);
  
  const hubSpot = new Promise((resolve, reject) => {
    marketingHubspot
    .addMemberToList(inscriptionDTO.event_marketing_list, inscriptionDTO)
    .then(function (result) {
      resolve(result.ID);
    })
    .catch(function (error) {
      console.log('error>>>>>', error);
      reject(error);
    });    
  });

  const sendinBlue = new Promise((resolve, reject) => {
    if (!inscriptionDTO.event_marketing_list) {
      // || !member.validated) {
      resolve(inscriptionDTO);
      } else {
        marketingSendinBlue
        .addMemberToList(inscriptionDTO.event_marketing_list, inscriptionDTO)
        .then(function (result) {
          resolve(result.ID);
        })
        .catch(function (error) {
          console.log('error>>>>>', error);
          reject(error);
        });
      }
  });

  try {
    return Promise.all(hubSpot, sendinBlue)
  } catch (error) {
    console.log("Error in _addMember:", error);
    // Manejar el error de manera apropiada
  }  
}

async function _deleteMember(idLista, email, inscription = undefined) {
  console.debug("Elimino miembro de la lista de marketing>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<", email, idLista);

  const hubSpot = new Promise((resolve, reject) => {
    resolve(marketingHubspot.deleteMemberFromList(idLista, email, inscription));
  });

  const sendinBlue = new Promise((resolve, reject) => {
    return new Promise(function (resolve, reject) {
      if (!idLista || !email) {
        resolve();
      } else {
        resolve(marketingSendinBlue.deleteMemberFromList(idLista, email));
      }
    });    
  });

  try{
  return Promise.all(hubSpot, sendinBlue);
  } catch (error) {
    console.log("Error in _addMember:", error);
    // Manejar el error de manera apropiada
  }
}

async function addMarketingList(dataUser, dataInscription) {
  dataInscription.user = dataUser.userResult.user;
  return _addMember(_generateMarketingDTO(dataInscription));
}

async function syncronizeEventWithMarketingList(eventId) {
  let result = false;
  try {
    let inscriptionsToSync = await eventInscriptionService._getInscriptionsWithoutMemberId(eventId);

    for (var i = 0; i < inscriptionsToSync.length; i++) {
      const item = inscriptionsToSync[i].get({
        plain: true,
      });
      //Adaptamos el objeto a lo que espera _generateMarketingDTO
      // dataInscription {incription:{...}, event:{...}, reservation:{...}, user:{...}}
      // en _getInscriptionsWithoutMemberId devuelve la inscripcion en el raiz
      item.inscription = item;
      sleep(1000 * i).then(function () {
        let inscriptionDTO = _addMember(_generateMarketingDTO(item));
        //                let marketingDTO = _generateMarketingDTO(item);
        //                console.log(marketingDTO)
        //                _deleteMember(marketingDTO.event_marketing_list, marketingDTO.email)
      });
    }

    result = true;
    return result;
  } catch (error) {
    console.log("No se ha podido _syncronizeEventWithMarketingList", error);
  }
}

function userToMarketingDTO(user) {
  const result = {};
  result.email = user.email ? user.email : "";
  result.name = user.name ? user.name : "";
  result.surname = user.surname ? user.surname : "";
  result.phone = user.phone ? user.phone : "";
  result.userId = user.id ? user.id : "";
  result.profile = user.profile ? user.profile : "";
  result.entity = user.Entity ? user.Entity.name : "";

  return result;
}

module.exports = {
  syncronizeEventWithMarketingList,
  addMarketingList,
  _deleteMember,
  _generateMarketingDTO,
  userToMarketingDTO,
};
