-module(test_client).

% API

-export([test/3]).

% Internal

-export([do_test/3]).

test(Node, Parallelizm, Count) when is_integer(Count), Count > 0 ->
    lists:foreach(
        fun(I) ->
            erlang:spawn(?MODULE, do_test, [Node, I, Count])
        end,
        lists:seq(1, Parallelizm)).

do_test(Node, Instance, Count) ->
    StartTime = get_tick_count(),
    {NSuccess, NFail} = do_test_repeat(Node, Count, {0, 0}),
    Time = (get_tick_count() - StartTime)/1000,
    Speed = if Time =/= 0.0 -> Count / Time; true -> 0.0 end,
    io:format("Client ~2w done. AvgTime=~.3f (~.3f c/s), Failed=~p, Success=~p~n",
                [Instance, Time / Count, Speed, NFail, NSuccess]).

do_test_repeat(_Node, 0, Stats) ->
    Stats;
do_test_repeat(Node, I, {S, F}) ->
    Stats = case test_server:ping(Node) of
            ok -> {S+1, F};
            _  -> {S, F+1}
            end,
    do_test_repeat(Node, I-1, Stats).

get_tick_count() ->
    {A,B,C} = now(),
    (A-1051) * 1000000000 + B * 1000 + C div 1000.

