// import modules
var mail = {},
    request = require('request'),
    logger = require('../../../logger'),
    semusiConfig = require('./../../config'),
    common = require('./../../utils/common.js'),
    sendgrid = require('sendgrid')(semusiConfig.sendGrid.emailId, semusiConfig.sendGrid.password);

sendgridd = require('@sendgrid/mail');
sendgridd.setApiKey(semusiConfig.emailInfo.sendGridApiKey);

mail.sendMail = function(message) {
    message.from = semusiConfig.sendGrid.emailId;
    message.fromname = "appICE";
    sendgridd.send(message, function(err, result) {
        if (err) {
            logger.error(`Error sending email => ${err}`);
            return;
        }
        logger.info(`result from send mail  :: => ${result}`);
         
    });
}
//Send Email Of OTP
mail.sendAuthInfo = function (emailId, OTP) {
    lookup(function (err, host) {
        const msg = {
            from: semusiConfig.emailInfo.from, // Use the email address or domain you verified above
            subject: 'OTP For Secure Login at appICE',
            personalizations: [
                {
                    "to": [
                        {
                            "email": emailId
                        }
                    ],
                    "dynamic_template_data": {
                        "OTP": OTP
                    }
                }
            ],
            template_id: semusiConfig.emailInfo.templateId.sendAppAuthInfo_id,
        };
        sendgridd.send(msg, function (err, result) {
            if (err) {
                logger.error(`Error sending email => ${err}`); 
                return;
            } else {
                logger.info(` success: otp email sent :: => ${result}`);
                return;
            }
        });
    });
}

// Send Email Of New Pwd
mail.sendUpdatedPassword = function (emailId, Password) {

    lookup(function (err, host) {
        const msg = {
            from: semusiConfig.emailInfo.from, 
            personalizations: [
                {
                    "to": [
                        {
                            "email": emailId
                        }
                    ],
                    "dynamic_template_data": {
                        "Password": Password,
                        "emailId":emailId
                    }
                }
            ],
            template_id: semusiConfig.emailInfo.templateId.resetPwdEmailT_id ,
        };
        sendgridd.send(msg, function (err, result) {
            if (err) {
                logger.error(`Error in Sending EmailPassword  => ${err}`);
                return;
            } else {
                logger.info(`Successfully Password email Sent  :: => ${result}`);
                return;
            }
        });
    });
}
mail.sendToNewMember = function(member, memberPassword) {
    logger.info('enter here member')
    lookup(function(err, host) {
        logger.error(`enter here member with error==>  ${err}`) 
        try {
            let email = new sendgrid.Email();
            email.addTo(member.email);
            if (semusiConfig.IsProduction) {
                email.addTo(semusiConfig.successGroup);
                email.addSubstitution(':name', [member.full_name]);
            }
            email.subject = 'Your AppICE Account';
            email.from = 'support@appice.io';
            email.text = 'appICE Team, \n #BeContextAware';
            email.html = 'appICE Team,<br/>' +
                '#BeContextAware';
            email.setFilters({
                "templates": {
                    "settings": {
                        "enable": 1,
                        "template_id": semusiConfig.emailInfo.templateId.sendToNewMember
                    }
                }
            });

            email.addSubstitution(':name', [member.full_name]); // sub = {keep: ['secret']}
            //email.addSubstitution(':download',["<a href='"+semusiConfig.host +"/dashboard?action=appsetting'>Download SDK's </a>"]);
            sendgrid.send(email, function(err, json) {
                if (err) {
                    logger.error(`error sending mail => ${err}`);
                } else {
                    logger.info(`new user email sent ==> ${json}`);
                    //Send a copy to admin ids.
                    if (semusiConfig.AdminIds.length > 0) {
                        mail.sendSignUpNotification(member);
                    }
                }
            });
        } catch (e) {
            logger.error(`Error while sendToNewMember  =>>> ${e}`);
        }
    });
};

mail.sendSignUpNotification = function(member) {
    lookup(function(err, host) {
        try {
            let emailCopy = new sendgrid.Email();
            semusiConfig.AdminIds.forEach(function(item) {
                emailCopy.addTo(item);
                emailCopy.addSubstitution(':name', [member.full_name]);
                emailCopy.addSubstitution(':email', [member.email]);
            });

            emailCopy.subject = 'New User has signed up';
            emailCopy.from = semusiConfig.sendGrid.helloID;
            emailCopy.text = 'Best, \n A fellow AppICE Admin';
            emailCopy.html = 'Best,<br/>' +
                'A fellow AppICE Admin';
            emailCopy.setFilters({
                "templates": {
                    "settings": {
                        "enable": 1,
                        "template_id": semusiConfig.emailInfo.templateId.sendSignUpNotification
                    }
                }
            });
            sendgrid.send(emailCopy, function(err, json) {

            });
        } catch (e) {
            logger.error(`error while sendSignUpNotification  =>>> ${e}`);
        }
    });
};

mail.sendAlertNotification = function(subject, text) {
    lookup(function(err, host) {
        try {
            let emailAlert = new sendgrid.Email();
            semusiConfig.AlertIds.forEach(function(item) {
                emailAlert.addTo(item);
            });

            emailAlert.subject = subject;
            emailAlert.from = semusiConfig.sendGrid.emailId;
            emailAlert.text = text;
            emailAlert.html = text;
            emailAlert.setFilters({
                "templates": {
                    "settings": {
                        "enable": 1,
                        "template_id": semusiConfig.emailInfo.templateId.sendAlertNotification
                    }
                }
            });
            sendgrid.send(emailAlert, function(err, json) {

            });
        } catch (e) {
            logger.error(`error while send sendAlertNotification  =>>> ${e}`);
        }
    });
};

mail.sendToUpdatedMember = function(member, memberPassword) {
    lookup(function(err, host) {
        let message = {
            to: member.email,
            subject: 'AppICE Account - Password Change',
            html: 'Hi ' + getUserFirstName(member) + ',<br/><br/>' +
                'Your password for your AppICE account on <a href="' + host + '">' + host + '</a> has been changed. Below you can find your updated account details;<br/><br/>' +
                'Username: ' + member.username + '<br/>' +
                'Password: ' + memberPassword + '<br/><br/>' +
                'Best,<br/>' +
                'A fellow AppICE Admin'
        };

        mail.sendMail(message);
    });
};

mail.sendPasswordResetInfo = function(hostname, member, prid) {
    lookup(function(err, host) {
        const msg = {
            to: member.email,
            from: semusiConfig.sendGrid.helloID,
            subject: 'AppICE Account - Password Reset',
            text: 'Best, \n A fellow AppICE Admin',
            html: `<b>Dear User,</b> <br> <br> <b>Click on this <a href="${hostname}/reset?prid=${prid}" >link</a> to reset your password.</b> <br><br> <b>Regards,</b> <br> <b>Customer Support Team</b>`,

        };
        sendgridd.send(msg, function(err, result) {
            if (err) {
                logger.error(`Error in Sending Email  =>>> ${err}`);
            } else {
                logger.info(`Successfully email Sent => :: > ${result}`);
            }
        });
    });
};

mail.sendPasswordSuccessResetInfo = function(member) {
    lookup(function(err, host) {
        const msg = {
            to: member.email,
            from: semusiConfig.sendGrid.helloID,
            subject: 'AppICE Account - Password Reset',
            text: 'Best, \n A fellow AppICE Admin',
            html: `Best, <br> A fellow AppICE Admin`,
            "template_id": semusiConfig.emailInfo.templateId.sendPwdSuccessResetInfo
        };
        sendgridd.send(msg, function(err, result) {
            if (err) {
                logger.error(`Error in Sending Email  =>>> ${err}`);
            } else {
                logger.info(`Successfully email Sent => :: > ${result}`); 
            }
        });
    });
};


mail.sendApprovedInfo = function(member, isapproved) {
    lookup(function(err, host) {
        if (isapproved) {
            try {
                let email = new sendgrid.Email();
                email.addTo(member.email);
                if (semusiConfig.IsProduction) {
                    email.addTo(semusiConfig.successGroup);
                    email.addSubstitution(':name', [member.full_name]);
                }
                email.subject = 'AppICE Account - Account Approved';
                email.from = semusiConfig.sendGrid.helloID;
                email.text = 'AppICE Admin \n support@appice.io';
                email.html = 'AppICE Admin<br/>' +
                    'support@appice.io';
                email.setFilters({
                    "templates": {
                        "settings": {
                            "enable": 1,
                            "template_id": semusiConfig.emailInfo.templateId.Account_Approved
                        }
                    }
                });

                email.addSubstitution(':name', [member.full_name]); // sub = {keep: ['secret']}

                sendgrid.send(email, function(err, json) {
                    if (err) {
                        logger.error(`error sending mail => ${err}`);  
                    } else {
                        logger.info(`approval email sent ==> ${json}`); 
                    }
                });
            } catch (e) {
                logger.error(`Error isapproved true sendApprovedInfo  => ${e}`);
            }
        } else {
            try {
                let email = new sendgrid.Email();
                email.addTo(member.email);
                email.subject = 'AppICE Account - Account Disapproved !';
                email.from = semusiConfig.sendGrid.helloID;
                email.text = 'Best, \n A fellow AppICE Admin';
                email.html = 'Best,<br/>' +
                    'A fellow AppICE Admin';
                email.setFilters({
                    "templates": {
                        "settings": {
                            "enable": 1,
                            "template_id": semusiConfig.emailInfo.templateId.Account_Disapproved
                        }
                    }
                });

                email.addSubstitution(':name', [member.full_name]); // sub = {keep: ['secret']}

                sendgrid.send(email, function(err, json) {
                    if (err) {
                        logger.error(`Error sending mail   => ${err}`);  
                    } else {
                        logger.info(`disapproved email sent  :: +> ${json}`); 
                    }
                });
            } catch (e) {
                logger.error(`Error isapproved false sendApprovedInfo  => ${e}`); 
            }
        }
    });
};

mail.sendStepsToDeveloper = function(devemailid, id, key, apikey, steps, a_name, i_name) {
    try {
        let email = new sendgrid.Email();
        email.addTo(devemailid);
        email.subject = 'AppICE Account - Developer Integration Steps';
        email.from = semusiConfig.sendGrid.helloID;
        email.text = 'Best, \n A fellow AppICE Admin';
        email.html = 'Best,<br/>' +
            'A fellow AppICE Admin';

        if (steps == 'andriod' || steps == 'both') {
            //  email.setFilters({
            //              "templates": {
            //                "settings": {
            //                  "enable": 1,
            //                  "template_id": "c0eee7c9-b669-43be-b62b-23df1ae7343a"
            //                }
            //              }
            //            });
            email.addSubstitution(':appname', [a_name]);
            email.addSubstitution(':appid', [id]);
            email.addSubstitution(':appkey', [key]);
            email.addSubstitution(':apikey', [apikey]);
        }
        if (steps == 'ios' || steps == 'both') {
            email.setFilters({
                "templates": {
                    "settings": {
                        "enable": 1,
                        "template_id": semusiConfig.emailInfo.templateId.sendStepsToDeveloper
                    }
                }
            });
            email.addSubstitution(':appname', [i_name]);
            email.addSubstitution(':appid', [id]);
            email.addSubstitution(':appkey', [key]);
            email.addSubstitution(':apikey', [apikey]);
        }
        logger.info(`Developer Email :: +> ${email}`);
        sendgrid.send(email, function(err, json) {
            if (err) {
                logger.error(`Error sending developer mail   => ${err}`); 
            } else {
                logger.info(`developer email sen :: => ${json}`);   
            }
        });
    } catch (e) {
        logger.error(`Error sending email   => ${e}`);
    } finally {

    }
};



function getUserFirstName(member) {
    let userName = (member.full_name).split(" "),
        userFirstName = "";

    if (userName.length == 0) {
        userFirstName = "there";
    } else {
        userFirstName = userName[0];
    }

    return userFirstName;
}

// validate host ip with lookup
let lookup = function(callback) {
    // If host is set in config.js use that, otherwise get the external IP from ifconfig.me
    if (semusiConfig.host) {
        callback(false, semusiConfig.host);
    } else {
        request('http://ifconfig.me/ip', function(error, response, body) {
            callback(error, body);
        });
    }
}

module.exports = mail;
