-module(phonebooth).

-behaviour(gen_server).

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

-import(freeswitch, [get_event_name/1]).

-export([launch/1]).

%% ======================================================================
%% GEN_SERVER CALLBACK FUNCTIONS
%% ======================================================================

init(_) ->
    io:format("INIT ~p~n", [self()]),
    {ok, init}.

handle_call(_Request, _From, State) ->
    io:format("HANDLE_CALL ~p~n", [self()]),
    {reply, ok, State}.

handle_cast(_Request, State) ->
    io:format("HANDLE_CAST ~p~n", [self()]),
    {noreply, State}.

handle_info(call_hangup, State) ->
    io:format("HANDLE_INFO ~p~n", [self()]),
    {stop, normal, State};
handle_info({call, {event, Info}}, init) ->
    io:format("HANDLE_INFO ~p~n", [self()]),
    {noreply, {hd(Info), init}};
handle_info({Kind, {event, Info}}, {UUID, State})
  when Kind == call; Kind  == call_event ->
    io:format("HANDLE_INFO ~p~n", [self()]),
    Name = get_event_name(Info),
    NewState = case Name of
                   "CHANNEL_EXECUTE_COMPLETE" ->
                       App = proplists:get_value("Application", Info),
                       process_event({executed, App}, UUID, Info, State);
                   "DTMF" ->
                       Digit = proplists:get_value("DTMF-Digit", Info),
                       process_event({dtmf, Digit}, UUID, Info, State);
                   _ ->
                       process_event(Name, UUID, Info, State)
               end,
    {noreply, {UUID, NewState}}.

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

terminate(_Reason, _) ->
    ok.

%% ======================================================================
%% INTERFACE FUNCTIONS
%% ======================================================================

%% This function is called by FreeSWITCH to obtain a Pid for a new call
launch(Ref) ->
    {ok, Pid} = gen_server:start(?MODULE, [], []),
    io:format("New request ~p, responding with ~p~n", [Ref, Pid]),
    {Ref, Pid}.

%% ======================================================================
%% INTERNAL FUNCTIONS
%% ======================================================================

process_event(Event, UUID, Info, State) ->
    io:format("event ~p, ~p, ~p, ~p~n", [Event, UUID, Info, State]),
    ok.
