// Using NAMI: https://github.com/marcelog/Nami/

var namiConfig = {
  host: "localhost",
  port: 5038,
  username: "admin",
  secret: "secret5"
};

var logger = require('log4js').getLogger('App.astools');
var nami = new (require("nami").Nami)(namiConfig);
var amiConnected = false;
/*
nami.on('namiEvent', function (event) { });
nami.on('namiEventDial', function (event) { });
nami.on('namiEventVarSet', function (event) { });
nami.on('namiEventHangup', function (event) { });
process.on('SIGINT', function () {
  nami.close();
  process.exit();
});
*/
nami.on('namiConnected', function (event) {
  //nami.send(new namiLib.Actions.CoreShowChannelsAction(), function(response){
  //  logger.debug(' ---- Response: ' + util.inspect(response));
  //});
  amiConnected = true;
});
nami.open();

/*
 'action':'originate',
 'channel':'SIP/myphone',
 'context':'default',
 'exten':1234,
 'priority':1,
 'variables':{
   'name1':'value1',
   'name2':'value2'
 }
*/
function asCallOriginate(data) {
  var to_number = data["to_number"];
  var connect_extn = data["connect_extn"];
  var record_call = data["record_call"];
  logger.info("New call to " + to_number + " from " + connect_extn + " call_record " + record_call);

  var action = new namiLib.Actions.Status();
  action.variables = {
    'action': 'originate',
    'channel':'SIP/' + to_number,
    'context':'click2call',
    'exten': connect_extn,
    'priority':1,
    'variables':{
      'call_record':record_call,
      'message':'',
      'tripid':0
    }
  };
  nami.send(action, function(response) {
    logger.debug("Call originated: " + response);
  });
}

function makeNewCall(data) {
  if (amiConnected) {
    asCallOriginate(data);
  }
  return amiConnected;
}

module.exports.makeNewCall = makeNewCall;

@@ -41,16 +41,47 @@
 og/Nami/
+%0Avar namiLib = require(%22nami%22);
 %0A%0Avar na
@@ -249,30 +249,20 @@
 new 
-(require(%22
 nami
-%22)
+Lib
 .Nami
-)
 (nam
@@ -1267,14 +1267,17 @@
 ons.
-Status
+Originate
 ();%0A
@@ -1289,63 +1289,18 @@
 ion.
-variables = %7B%0A    'action': 'originate',%0A    '
 channel
-':
+ = 
 'SIP
@@ -1317,25 +1317,30 @@
 mber
-,%0A    '
+;%0A  action.
 context
-':'
+ = %22
 clic
@@ -1349,23 +1349,27 @@
 call
-',%0A    '
+%22;%0A  action.
 exten
-':
+ =
  con
@@ -1381,33 +1381,19 @@
 extn
-,%0A    'priority':1,%0A    '
+;%0A  action.
 vari
@@ -1397,22 +1397,21 @@
 ariables
-':%7B%0A  
+ = %7B%0A
     'cal
@@ -1437,18 +1437,16 @@
 ll,%0A    
-  
 'message
@@ -1455,18 +1455,16 @@
 '',%0A    
-  
 'tripid'
@@ -1472,16 +1472,69 @@
 0%0A  
-  %7D%0A  %7D;
+%7D;%0A  standardSend(action);%0A%7D%0A%0Afunction standardSend(action) %7B
 %0A  n
@@ -1550,32 +1550,33 @@
 action, function
+ 
 (response) %7B%0A   
@@ -1593,30 +1593,42 @@
 bug(
-%22Call originated: %22
+' ---- Response: '
  + 
+util.inspect(
 resp
@@ -1632,16 +1632,17 @@
 esponse)
+)
 ;%0A  %7D);%0A

update call function use nami