%% Author: mark
%%
%% Created: Mar 8, 2010
%%
%% Description:
%%		This callback is executed when someone dials in to an eavesdrop
%%
-module(pbx_eavesdrop).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([start/0, run/0, launch/1]).

-include_lib("figure/include/gut.hrl").
-include_lib("pbx/include/pbx_mnesia.hrl").

start() ->
	Pid = spawn( ?MODULE, run, [] ),
	register( ?MODULE, Pid ),
	syslog:debug( "pbx_eavesdrop:start() Started eavesdrop thread ~p~n", [Pid] ),
	{ ok, Pid }.

run() ->
	receive
		{ call, Data } ->
			{ event, [UUID | Rest]} = Data,
			EavesdropExtension = proplists:get_value( "variable_eavesdrop_extension", Rest ),
%%			syslog:debug( "pbx_eavesdrop:run() Rest=~p~n", [Rest] ),
			syslog:debug( "pbx_eavesdrop:run() New eavesdrop received for extension=~p~n", [EavesdropExtension] ),
			case pbx_mnesia:lookupOperatorByExtension( EavesdropExtension ) of
				{ ok, ExtensionRegistry } ->
					case proplists:is_defined( "execute-app-name", Rest ) of
						true ->
							PropsNoAppName = proplists:delete( "execute-app-name", Rest );
						_ ->
							PropsNoAppName = Rest
					end,
					case proplists:is_defined( "execute-app-arg", PropsNoAppName ) of
						true ->
							PropsNoAppArg = proplists:delete( "execute-app-arg", PropsNoAppName );
						_ ->
							PropsNoAppArg = PropsNoAppName
					end,
					PropsWithAppName = PropsNoAppArg ++
						[ proplists:property( "execute-app-name", "eavesdrop" ) ],
					PropsWithAppArg = PropsWithAppName ++
						[ proplists:property( "execute-app-arg",
							ExtensionRegistry#pbx_operator_registry.operator_uuid ) ],
%%					syslog:debug( "pbx_eavesdrop:run() sendmsg( ~p, ~p )~n", [ UUID, PropsWithAppArg ] ),
					EavesdropResult = pbx:sendmsg( UUID, PropsWithAppArg ),
					syslog:debug( "pbx_eavesdrop:run() EavesdropResult = ~p~n", [EavesdropResult] );
				Error ->
					%% Operator not logged in to extension
					syslog:info( "pbx_eavesdrop:run() Could not locate extension ~s, Error ~p~n", [ EavesdropExtension, Error ] ),
					_ResultHangup = pbx:bgapi( sched_hangup, "+1 " ++ UUID )
			end,
			run();
		{call_event, Data} ->
			{ event, [UUID | Rest]} = Data,
			EventName = proplists:get_value( "Event-Name", Rest ),
			syslog:debug( "pbx_eavesdrop:run() call_event UUID=~p, EventName=~p~n", [UUID, EventName] ),
			run();
		{get_pid, _UUID, Ref, Pid} ->
			NewPid = spawn( ?MODULE, run, [] ),
			syslog:debug( "pbx_eavesdrop:run() Request to spawn new handler process, returning PID ~p~n", [NewPid] ),
			Pid ! { Ref, NewPid },
			run()
	end.

launch( Ref ) ->
	NewPid = spawn( ?MODULE, run, [] ),
	syslog:debug( "pbx_eavesdrop:launch() Returning new PID ~p~n", [NewPid] ),
	{Ref, NewPid}.