const SibApiV3Sdk = require('sib-api-v3-sdk');
const config = require('../config');

const defaultClient = SibApiV3Sdk.ApiClient.instance;

// Configure API key authorization: api-key
const apiKey = defaultClient.authentications['api-key'];
apiKey.apiKey = config.sendinblue.API_KEY;


/**
 * Enviar un email transaccional
 * @header
 *   @param {number} data.to - Email destino
 *   @param {number} data.name - Nombre del contacto destino
 *   @param {number} data.subject - Asunto
 * @body
 *   @param {number} data.TemplateID
 *   @param {number} data.Variables
 * @return {Promise}
 *
 */

function sendEmailTransactional(header, body) {

    if (header === undefined || header === null) {
        throw new Error("Missing the required parameter 'header' when calling sendEmailTransactional");
    };

    if (body === undefined || body === null) {
        throw new Error("Missing the required parameter 'body' when calling sendEmailTransactional");
    };


    let apiInstance = new SibApiV3Sdk.TransactionalEmailsApi();
    let sendSmtpEmail = new SibApiV3Sdk.SendSmtpEmail();

    sendSmtpEmail.templateId = body.TemplateID;

    sendSmtpEmail.sender = { name: 'Fundación Lo Que De Verdad Importa', email: 'info@loquedeverdadimporta.org' };
    sendSmtpEmail.to = [{ name: header.name, email: header.to }];
    if (header.bcc) { sendSmtpEmail.bcc = [{ name: header.bccName, email: header.bcc }] };

    sendSmtpEmail.subject = header.subject;
    sendSmtpEmail.params = body.Variables;

    apiInstance.sendTransacEmail(sendSmtpEmail).then(function (data) {
        console.log('API called successfully. Returned data: ' + JSON.stringify(data));
    }, function (error) {
        console.error(error);
    });
}

function _existsMember(userEmail) {
    const api = new SibApiV3Sdk.ContactsApi();

    return new Promise(function (resolve, reject) {
        console.debug('_existsMember:');
        console.debug(userEmail);

        api.getContactInfo(userEmail)
            .then(function (data) {
                console.debug('API called successfully. Returned data: ' + data);
                resolve(data);
            })
            .catch(function (error) {
                console.error(error);
                reject(error);
            });
    });    
}


function _createMember(member) {
    const api = new SibApiV3Sdk.ContactsApi();

    return new Promise(function (resolve, reject) {
        const createContact = new SibApiV3Sdk.CreateContact(); // CreateContact | Values to create a contact

        createContact.email = member.email;
        createContact.updateEnabled = true; // <- Actualiza el contacto si existe ese email
        createContact.attributes = {
            NOMBRE: member.name,
            APELLIDOS: member.surname,
            SMS: member.phone,
            SOURCE: member.source,
            USERID: member.userId,
            ENTITYNAME: (member.entity) ? member.entity : '',
            RESERVATIONCODE: (member.reservation_code) ? member.reservation_code : '',
            TICKETCODE: member.code_ticket,
            VALIDATED: (member.validated) ? 1 : 0,
            //COLOR: (member.color) ? member.color : '',
            //DESCOLOR: member.description,
        }

        console.debug('_createMember:');
        console.debug(createContact);

        api.createContact(createContact)
            .then(function (data) {
                console.debug('API called successfully. Returned data: ' + data);
                if (data && data.id) {
                    // Se ha dado de alta el contacto porque no existía
                    createContact.ID = data.id;
                }
                resolve(createContact);
            })
            .catch(function (error) {
                console.error(error);
                reject(error);
            });
    });
};

function _updateMember(email, member) {
    const api = new SibApiV3Sdk.ContactsApi();

    return new Promise(function (resolve, reject) {
        const updateContact = new SibApiV3Sdk.UpdateContact();

        updateContact.attributes = {
            NOMBRE: member.name,
            APELLIDOS: member.surname,
            SMS: member.phone,
            EMAIL: member.email,
            ENTITYNAME: (member.entity) ? member.entity : '',
        }

        api.updateContact(email, updateContact)
            .then(function (data) {
                console.debug('API called successfully. Returned data: ' + data);
                resolve(updateContact);
            })
            .catch(function (error) {
                console.error(error);
                reject(error);
            });
    });
};

function _deleteMember(email) {
    const api = new SibApiV3Sdk.ContactsApi();

    return new Promise(function (resolve, reject) {

        api.deleteContact(email)
            .then(function (data) {
                console.debug('API called successfully. Returned data: ' + data);
                resolve();
            })
            .catch(function (error) {
                console.log(error);
                reject(error);
            });
    });
};

function _addMemberToList(member, listId) {
    const api = new SibApiV3Sdk.ContactsApi();

    const contactEmails = new SibApiV3Sdk.AddContactToList(); // AddContactToList | Emails addresses of the contacts
    contactEmails.emails = [member.email];

    return new Promise(function (resolve, reject) {
        api.addContactToList(listId, contactEmails)
            .then(function (data) {
                console.debug('API called successfully. Returned data: ' + data);
                if ((data.contacts.success) && (data.contacts.success[0] === member.email)) {
                    resolve(data.contacts.success[0])
                } else reject()
            })
            .catch(function (error) {
                reject(error)
            })
    });
}

function _removeMemberFromList(member, listId) {
    const api = new SibApiV3Sdk.ContactsApi();

    const contactEmails = new SibApiV3Sdk.RemoveContactFromList(); // RemoveContactFromList | Emails adresses of the contact
    contactEmails.emails = [member];

    return new Promise(function (resolve, reject) {
        api.removeContactFromList(listId, contactEmails)
            .then(function (data) {
                console.debug('API called successfully. Returned data: ' + data);
                if ((data.contacts.success) && (data.contacts.success[0] === member)) {
                    resolve(data.contacts.success[0])
                } else reject()
            })
            .catch(function (error) {
                reject(error)
            })
    });
}

function getLists() {
    const api = new SibApiV3Sdk.ContactsApi();
    return new Promise(function (resolve, reject) {
        api.getAccount().then(function (data) {
            console.debug('API called successfully. Returned data: ' + data);
            var opts = {
                'limit': 10, // Number | Number of documents per page
                'offset': 0 // Number | Index of the first document of the page
            };
            api.getLists(opts)
                .then(function (data) {
                    resolve(data.lists);
                })
                .catch(function (error) {
                    reject(error)
                })

        }, function (error) {
            reject(error)
        });
    });
};


function addMemberToList(listId, member) {
    return new Promise(function (resolve, reject) {
        _createMember(member)
            .then(function (contact) {
                console.debug('añadir a lista: ' + listId + '  *  ' + contact);
                return _addMemberToList(contact, listId);
            })
            .then(function () {
                resolve(true);
            })
            .catch(function (error) {
                console.error(error);
                reject(error);
            });
    })
};

function deleteMemberFromList(listId, member) {
    return _removeMemberFromList(member, listId);
}


function updateMemberByEmail(userEmail, userData) {
    return _updateMember(userEmail, userData);
}

function deleteMemberByEmail(userEmail) {
    return _deleteMember(userEmail);
}

function getMemberByEmail(userEmail) {
    return _existsMember(userEmail);

}

module.exports = {
    sendEmailTransactional,
    getLists,
    addMemberToList,
    deleteMemberFromList,
    updateMemberByEmail,
    deleteMemberByEmail,
    getMemberByEmail
}

