-module(freeswitch_bind).

-behaviour(gen_server).

-record(st, {fsnode, pbxpid, configpid, dirpid, dialpid}).

-export([start/3, terminate/2, code_change/3, init/1,
	 handle_call/3, handle_cast/2, handle_info/2]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% gen_server methods
start(Node, Section, Pid) ->
    gen_server:start(?MODULE, [Node, Section, Pid], []).

init([Node, Section, Pid]) ->
	io:format( "freeswitch_bind:init( [Node=~w, Section=~w, Pid=~w])~n", [Node, Section, Pid] ),
    {api, Node} ! {bind, Section},
    receive
	ok ->
		{ok, ConfigurationPid } = freeswitch:start_fetch_handler( Node, configuration, freeswitch_callback, fetch_handler ),
		{ok, DirectoryPid } = freeswitch:start_fetch_handler( Node, directory, freeswitch_callback, fetch_handler ),
		{ok, DialplanPid } = freeswitch:start_fetch_handler( Node, dialplan, freeswitch_callback, fetch_handler ),
	    {ok, #st{fsnode=Node, pbxpid=Pid, configpid=ConfigurationPid, dirpid=DirectoryPid, dialpid=DialplanPid}};
	{error, Reason} ->
	    {stop, {error, {freeswitch_error, Reason}}}
    after 5000 ->
	    {stop, {error, freeswitch_timeout}}
    end.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%%
%%	If the request isn't recognized, just log it and do nothing.
%%
handle_call(Request, _From, State) ->
    io:format("freeswitch_bind:handle_call( ~w, _From, State) unrecognized request~n",
		[Request]),
    {reply, {error, unrecognized_request}, State}.

handle_cast(Message, State) ->
    error_logger:error_msg("~p received unrecognized cast ~p~n",
			   [self(), Message]),
    {noreply, State}.


handle_info({fetch, Section, Tag, Key, Value, FetchID, Params}, #st{fsnode=Node, pbxpid=Pid}=State) ->
    {ok, Xml} = freeswitch_callback:xml_fetch( {fetch, Section, Tag, Key, Value, Params} ),
%%	{ok, XML} = gen_server:call(Pid, {fetch, Section, Tag, Key, Value, Params}),
    {api, Node} ! {fetch_reply, FetchID, Xml},
    receive
	ok ->
	    {noreply, State};
	{error, Reason} ->
	    {stop, {error, Reason}, State}
  end;
handle_info(Info, State) ->
	io:format( "freeswitch_bind:handle_info() Info=~w~n", [Info]),
    {noreply, State}.
