var AddExtensions = function(companyId, tenantId, obj, callback)
{
    try
    {
        dbModel.Extension.findAll({where :[{CompanyId: companyId},{TenantId: tenantId}]})
            .then(function (list)
            {
                for (i = 0; i < list.length; i++)
                {
                    AddExtensionWithMappingId(companyId, tenantId, list[i].ObjCategory, list[i], function(ee)
                    {

                    });
                    redisHandler.SetObject('EXTENSIONBYID:' + tenantId + ':' + companyId + ':' + list[i].id, JSON.stringify(list[i]), function(err, res)
                    {
                        console.log('EXTENSIONBYID ADDED');
                    });

                }

                callback(obj)

            })
            .catch(function(err)
            {
                callback(obj)
            });
    }
    catch(ex)
    {
        callback(obj)
    }
};
var GetFullQualifiedSipUri = function (tenantId, companyId, destination, res) {

    dbmodel.Extension.find({
        where: [{Extension: destination}, {TenantId: tenantId}, {CompanyId: companyId}],
        include: [
            {model: dbmodel.SipUACEndpoint, as: "SipUACEndpoint"},
            {model: dbmodel.CloudEndUser, as: "CloudEndUser"}
        ]
    }).then(function (user) {
        if (user) {
            return user.SipUACEndpoint.SipUsername + "@" + user.CloudEndUser.Domain;
        }
        else {
            return null;
        }
    }).catch(function (err) {
        logger.error("DVP-GetFullQualifiedSipUri PGSQL %s failed", destination, err);
        res.write(messageFormatter.FormatMessage(err, "Extension NotFound or error", false, undefined));
        res.end();
    });

};
var AddExtensionWithMappingId = function(companyId, tenantId, extType, ext)
{
    try
    {

        if(extType === 'USER')
        {
            dbModel.Extension.find({where :[{CompanyId: companyId},{TenantId: tenantId},{Extension: ext.Extension}], include:[{model: dbModel.SipUACEndpoint, as: "SipUACEndpoint"}]})
                .then(function (extension)
                {
                    if(extension && extension.SipUACEndpoint)
                    {
                        var extStr = JSON.stringify(ext);

                        var extObj = JSON.parse(extStr);

                        extObj.MappingID = extension.SipUACEndpoint.id;

                    }

                    redisHandler.SetObject('EXTENSION:' + tenantId + ':' + companyId + ':' + extension.Extension, JSON.stringify(extObj), function(err, res)
                    {
                        console.log('EXTENSION ADDED');
                    });



                }).catch(function(err)
                {
                    console.log(err);
                });
        }
        else if(extType === 'GROUP')
        {
            dbModel.Extension.find({where :[{CompanyId: companyId},{TenantId: tenantId},{Extension: ext.Extension}], include:[{model: dbModel.UserGroup, as: "UserGroup"}]})
                .then(function (extension)
                {
                    if(extension && extension.UserGroup)
                    {
                        var extStr = JSON.stringify(ext);

                        var extObj = JSON.parse(extStr);

                        extObj.MappingID = extension.UserGroup.id;

                    }

                    redisHandler.SetObject('EXTENSION:' + tenantId + ':' + companyId + ':' + extension.Extension, JSON.stringify(extObj), function(err, res)
                    {
                        console.log('EXTENSION ADDED');
                    });



                }).catch(function(err)
                {
                    console.log(err);
                });

        }
        else
        {
            redisHandler.SetObject('EXTENSION:' + tenantId + ':' + companyId + ':' + ext.Extension, JSON.stringify(ext), function(err, res)
            {
                console.log('EXTENSION ADDED');
            });
        }


    }
    catch(ex)
    {
        console.log(ex);

    }



}
                            request(options, function (error, response, body)
                            { // Create Cart
                                if (error)
                                {
                                    var instance = messageFormatter.FormatMessage(error, "create_uuid", false, body);
                                    res.end(instance);
                                }
                                else
                                {
                                    //var options = format("{{return_ring_ready=false,origination_uuid={0},origination_caller_id_number={1},DVP_ACTION_CAT={2},DVP_OPERATION_CAT=PRIVATE_USER,companyid={3},tenantid={4},Other-Leg-Unique-ID={5}}", reqId, channelId, dvpActionCat, companyId, tenantId, channelId);

                                    var dialoption = format("return_ring_ready=false,origination_uuid={0},origination_caller_id_number={1},DVP_ACTION_CAT={2},DVP_OPERATION_CAT=PRIVATE_USER,companyid={3},tenantid={4},DVP_CALLMONITOR_OTHER_LEG={5}", reqId, channelId, dvpActionCat, companyId, tenantId, channelId);

                                    logger.debug('[DVP-MonitorRestAPI.CallDispatch] - [%s] - options : %s', reqId, dialoption);

                                    if (protocol.toLowerCase() == "user")
                                    {

                                        dbmodel.Extension.find({
                                            where: [{Extension: destination}, {TenantId: tenantId}, {CompanyId: companyId}],
                                            include: [
                                                {
                                                    model: dbmodel.SipUACEndpoint, as: "SipUACEndpoint",
                                                    include: [
                                                        {model: dbmodel.CloudEndUser, as: "CloudEndUser"}
                                                    ]
                                                }
                                            ]

                                        }).then(function (user)
                                        {
                                            if (user)
                                            {
                                                var tempURL = user.SipUACEndpoint.SipUsername + "@" + user.SipUACEndpoint.CloudEndUser.Domain;

                                                destination = tempURL ? format("user/{0}", tempURL) : format("user/{0}", destination);

                                                var command = util.format("originate? {%s}%s %s", dialoption, destination, data);

                                                //var command = format("originate? {0}{1} {2}", dialoption, destination, data);

                                                logger.debug('[DVP-MonitorRestAPI.CallDispatch] - [%s] - command : %s', reqId, command);

                                                var options = {
                                                    method: 'GET',
                                                    uri: "http://" + ip + ":8080/webapi/" + command,
                                                    headers: {
                                                        'Content-Type': 'application/json',
                                                        'Accept': 'application/json',
                                                        'Authorization': 'Basic ' + new Buffer(config.FreeSwitch.userName + ':' + config.FreeSwitch.password).toString('base64')
                                                    }
                                                };

                                                request(options, function (error, response, body) { // Create Cart

                                                    if (error) {
                                                        var instance = messageFormatter.FormatMessage(error, "SendGetCommandToCallServer", false, body);
                                                        res.end(instance);
                                                    }
                                                    else {

                                                        if(body){
                                                            var dataArr = body.split(" ");

                                                            if(dataArr.length > 1 ){

                                                                body = dataArr[1].trim();
                                                            }
                                                        }

                                                        var instance = messageFormatter.FormatMessage(undefined, "SendGetCommandToCallServer", true, body);
                                                        res.end(instance);
                                                    }
                                                });
                                            }
                                            else {
                                                return null;
                                            }
                                        }).catch(function (err) {
                                            logger.error("DVP-GetFullQualifiedSipUri PGSQL %s failed", destination, err);
                                            res.write(messageFormatter.FormatMessage(err, "Extension NotFound or error", false, undefined));
                                            res.end();
                                        });

                                    }
                                    else {

                                        var command = format("originate? {0}{1} {2}", options, destination, data);

                                        var options = {
                                            method: 'GET',
                                            uri: "http://" + ip + ":8080/webapi/" + command,
                                            headers: {
                                                'Content-Type': 'application/json',
                                                'Accept': 'application/json',
                                                'Authorization': 'Basic ' + new Buffer(config.FreeSwitch.userName + ':' + config.FreeSwitch.password).toString('base64')
                                            }
                                        };

                                        request(options, function (error, response, body) { // Create Cart
                                            if (error) {
                                                var instance = messageFormatter.FormatMessage(error, "send msg", false, body);
                                                res.end(instance);
                                            } else {

                                                if(body){
                                                    var dataArr = body.split(" ");

                                                    if(dataArr.length > 1 ){

                                                        body = dataArr[1].trim();
                                                    }
                                                }

                                                var instance = messageFormatter.FormatMessage(undefined, "SendGetCommandToCallServer", true, body);
                                                res.end(instance);
                                            }
                                        });


                                    }

                                }
                            });