const moment = require("moment");
const Mailchimp = require("mailchimp-api-v3");
const mailchimp_key = "7d4ffd805bdb43a34f0806c0d2970e73-us3";
//moment = require('moment'),
//    _ = require('lodash'),
//    conf = require('../conf');

//var logger = require("../helpers/logger");

const mailchimp = new Mailchimp(mailchimp_key);

function getLists() {
  return new Promise(function (resolve, reject) {
    console.log("voy a llamar a la API");
    mailchimp
      .get("/lists", {
        fields: "lists.id,lists.name",
        sort_field: "date_created",
        sort_dir: "DESC",
        since_date_created: moment("2019-02-14").format("YYYY-MM-DD"),
      })
      .then(function (results) {
        resolve(results.lists);
      })
      .catch(function (error) {
        reject(error);
      });
  });
}
/*

function getMembers(listId) {
    return new Promise(function (resolve, reject) {
        console.log('getMembers => ', '/lists/' + listId + '/members');
        mailchimp.get('/lists/' + listId + '/members', {
            fields: 'members.id,members.email_address,members.merge_fields',
        })
            .then(function (results) {
                resolve(results.members);

            })
            .catch(function (error) {
                reject(error)
            })
    });
}
*/

function getMember(listId, member) {
  return new Promise(function (resolve, reject) {
    console.debug("getMember => ", "/search-members", listId, " email: " + member.EMAIL);
    mailchimp
      .get("/search-members", {
        list_id: listId,
        query: member.EMAIL,
        fields: ["email_address"],
      })
      .then(function (results) {
        if (results && results.exact_matches && results.exact_matches.total_items == 1) {
          console.log("getMember => ", results.exact_matches.members[0].id);
          resolve(results.exact_matches.members[0]);
        } else reject();
      })
      .catch(function (error) {
        reject(error);
      });
  });
}

function addMember(listId, member) {
  return new Promise(function (resolve, reject) {
    //        logger.debug('addMember => ', '/lists/' + listId + '/members', ' email: ' + member.email);
    console.log("addMember => ", "/lists/" + listId + "/members", " email: " + member.email);

    var memberMailchimp = {
      EMAIL: member.email,
      FNAME: member.name,
      LNAME: member.surname,
      SOURCE: member.source,
      RESERCODE: member.reservation_code ? member.reservation_code : "",
      TICKETCODE: member.code_ticket,
      VALIDATED: member.validated ? 1 : 0,
      COLOR: member.color ? member.color : "",
      DESCOLOR: member.description,
      ENTITYNAME: member.entity ? member.entity : "",
      USERID: member.userId,
    };

    console.log("addMember: En MailChimp");
    console.log(listId, memberMailchimp);

    mailchimp
      .post("/lists/" + listId + "/members", {
        email_address: memberMailchimp.EMAIL,
        merge_fields: memberMailchimp,
        status: "subscribed",
      })
      .then(function (results) {
        console.log("addMember => ", memberMailchimp.EMAIL, results.id, results.statusCode);
        memberMailchimp.ID = results.id;
        resolve(memberMailchimp);
      })
      .catch(function (error) {
        console.log("addMember => ", error.title, error.status);
        if (error.status == 400 && error.title == "Member Exists") {
          resolve(getMember(listId, memberMailchimp));
        } else {
          console.log(error);
          reject(error);
        }
      });
  });
}

function deleteMember(listId, memberId) {
  return new Promise(function (resolve, reject) {
    console.debug("deleteMember => ", "/lists/" + listId + "/members/" + memberId);
    mailchimp
      .delete("/lists/" + listId + "/members/" + memberId)
      .then(function (results) {
        resolve(results);
      })
      .catch(function (error) {
        if (error.status == 404) {
          // Miembro no existe
          resolve({});
        } else {
          reject(error);
        }
      });
  });
}

module.exports = {
  getLists,
  addMember,
  deleteMember,
};

//module.exports.getMembers = getMembers;
