%% Author: mark
%%
%% Created: Mar 18, 2010
%%
%% Description:
%%		This server function allows the client to have Freeswitch initiate
%%		an eavesdrop call to the manager's extension.  It is assumed
%%		that the manager isn't on the phone or logged in as an operator
%%		when they initiate the eavesdrop session.
%%
-module(pbx_eavesdrop).

%%
%% Exported Functions
%%
-export([callManager/2]).
-export([functions/0, variables/0]).
-export([fsfuns/0, fsvars/0, fsnodes/0]).

%%
%% Include files
%%
-include_lib("figure/include/gut.hrl").

callManager( _Data, [[SessionCookie, #str{s=ManagerExtension}, #str{s=OperatorUUID} ]] ) ->
	case storage:isSessionManagerUser( SessionCookie ) of
		true ->
			{ ok, DialerLocalPrefix } = mnesia_sofia:getSofiaConfigValue( dialerLocalPrefix ),
			{ ok, DialerLocalSuffix } = mnesia_sofia:getSofiaConfigValue( dialerLocalSuffix ),
			OriginateCmd = DialerLocalPrefix ++ ManagerExtension ++ DialerLocalSuffix ++ " '&eavesdrop( " ++ OperatorUUID ++ " )'",
			syslog:debug( "pbx_eavesdrop:callManager() OriginateCmd is \"~s\"~n", [OriginateCmd] ),
			case pbx:api( originate, OriginateCmd ) of
				{ ok, ResultStrA } ->
					LenA = string:len( ResultStrA ),
					UuidA = string:substr( ResultStrA, 5, LenA - 5 ),
					syslog:debug( "pbx_eavesdrop:callManager() UUID A is \"~s\"~n", [ UuidA ] ),
					[ ok, UuidA ];
				Error ->
					syslog:error( "pbx_eavesdrop:callManager() Error trying to originate eavesdrop -- ~p~n", [Error] ),
					[ error, eavesdrop_failed ]
			end;
		_ ->
			syslog:error( "pbx_eavesdrop:callManager() Permission denied~n" ),
			[ error, permission_denied ]
	end.

functions() ->
    [func(callManager)].

variables() ->
	[].

fsfuns() ->
    [func(callManager)].
    
fsvars() ->
	[].

fsnodes() ->
    nd(str("PBX Eavesdrop"),
      [{program, nd(str("PBXEavesdrop"),
			[{function, nd(str("PBX Eavesdrop Functions"), fsfuns())},
			 {variable, nd(str("PBX Eavesdrop Variables"), fsvars())}])}
      ]).
