%% Author: mark
%% Created: Feb 23, 2010
%% Description: TODO: Add description to pbx_callback
-module(pbx_callback).

%%
%% Include files
%%

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

start() ->
	Pid = spawn( ?MODULE, run, [] ),
	register( ?MODULE, Pid ),
	{ ok, Pid }.

run() ->
	receive
		{ call, Data } ->
			{ event, [UUID | Rest]} = Data,
			syslog:debug( "pbx_callback:run() New call received, UUID=~p, Rest=~p~n", [UUID, Rest] ),
			AnswerResults = pbx:api( eval, "uuid:" ++ UUID ++ " answer" ),
			syslog:debug( "pbx_callback:run() AnswerResults=~p~n", [AnswerResults] ),
			GetPinResults = pbx:api( eval, "uuid:" ++ UUID ++ " play_and_get_digits 4 4 1 5000 # /opt/freeswitch/sounds/en/us/callie/conference/8000/conf-pin.wav /opt/freeswitch/sounds/en/us/callie/conference/8000/conf-bad-pin.wav operator_pin \\d+" ),
			syslog:debug( "pbx_callback:run() GetPinResults=~p~n", [GetPinResults] ),
			GetPinVarResults = pbx:api( uuid_getvar, UUID ++ " operator_pin" ),
			syslog:debug( "pbx_callback:run() GetPinVarResults=~p~n", [GetPinVarResults] ),
			run();
		{call_event, Data} ->
			{ event, [UUID | Rest]} = Data,
			Name = proplists:get_value( "Event-Name", Rest ),
			syslog:debug( "pbx_callback:run() call_event UUID=~p, Name=~p, Rest=~p~n", [UUID, Name, Rest] ),
			run();
		{get_pid, UUID, Ref, Pid} ->
			NewPid = spawn( ?MODULE, run, [] ),
			syslog:debug( "pbx_callback: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_callback:launch() Returning new PID ~p~n", [NewPid] ),
	{Ref, NewPid}.