'use strict';

var messageBirdConf = config.get("phone");
var messagebird;

if(messageBirdConf) {
    messagebird = require('messagebird')(messageBirdConf.messageBirdOptions.key);
}

var msg;

function sendSMS(targetNum, message, callback) {
    if(messagebird) {
        var params = {
            'originator': messageBirdConf.originator,
            'recipients': targetNum,
            'body': message
        };

        messagebird.messages.create(params, function (err, response) {
            callback(err, response);
        });
    } else {
        msg = generateErrorMessage();
        callback(msg);
    }
};

function validateNumber(targetNum, callback) {
	if (messagebird) {
		messagebird.lookup.read(targetNum, function (err, response) {
			callback(err, response);
		});
	} else {
		msg = generateErrorMessage();
        callback(msg);
	}
};

function generateErrorMessage() {
	var returnMsg = "!!! There is no configured SMS provider in serverConfiguration !!!!";
	var errMsg = "Please configure inside 'phone' field with " + 
				"syntax: 'messageBird' : { 'originator' : 'Fieldtec', 'key' : 'live_key' }";
    logger.error(returnMsg);
    logger.error(errMsg);	
    return returnMsg;
};

module.exports = {
    sendSMS: sendSMS,
    validateNumber: validateNumber
};