-module(cth_ctrl).

-export([proceed/0,
	 init/2, terminate/1]).

%%%===================================================================
%%% API
%%%===================================================================

proceed() ->
    ?MODULE ! proceed.

%%--------------------------------------------------------------------
%% Hook functions
%%--------------------------------------------------------------------
init(_Id, _Opts) ->
    WhoAmI = self(),
    DispPid = spawn_link(fun() -> dispatcher(WhoAmI) end),
    register(?MODULE, DispPid),
    io:format(user,
	      "~n~n+++ Startup finished, call ~w:proceed() to run tests!~n~n",
	      [?MODULE]),
    start_external_logger(cth_logger),
    receive
	{?MODULE,proceed} -> ok
    after
	10000 ->
	    ok
    end,
    {ok,[],ct_last}.

terminate(_State) ->
    io:format(user,
	      "~n~n+++ Tests finished, call ~w:proceed() to shut down!~n~n",
	      [?MODULE]),
    receive
	{?MODULE,proceed} -> ok
    after
       10000 ->
	    ok
    end,
    stop_external_logger(cth_logger),
    stop_dispatcher(),
    ok.

%%%===================================================================
%%% Internal functions
%%%===================================================================

start_external_logger(Name) ->
    case whereis(Name) of
	undefined -> ok;
	Pid -> exit(Pid, kill)
    end,
    spawn(fun() -> init_logger(Name) end).

stop_external_logger(Name) ->
    catch exit(whereis(Name), kill).

init_logger(Name) ->
    register(Name, self()),
    logger_loop(1).

logger_loop(N) ->
    ct:pal("Logger iteration: ~p", [N]),
    error_logger:error_report(N),
    timer:sleep(1000),
    logger_loop(N+1).

%%%-----------------------------------------------------------------

dispatcher(SendTo) ->
    receive Msg -> SendTo ! {?MODULE,Msg} end,
    dispatcher(SendTo).

stop_dispatcher() ->
    catch exit(whereis(?MODULE), kill).
	    

