-module(echoclient).
-export([connect/1, spawn_client/2, send_n_recv/2, measure/0, stop/0, get_rec/1]).
-export([init_database/0, start_mnesia/0, avg_list/0, init/2, avg_all/1]).
-define(serverIP, "192.168.1.102").
-define(serverPort, 1500).
-record(avglist,{pid, avg}).

spawn_client(N, M) ->
	if N =/= M ->
		spawn_link(echoclient, connect, [N]),
		spawn_client(N+1, M);
	   N =:= M ->
	   	spawn_link(echoclient, connect, [N]),
	   	io:format("Bye Bye spawn_client : got ~p~n", [N]) 
	end.
	

connect(N) ->
	case gen_tcp:connect(?serverIP,?serverPort,[binary,{packet,0},{active, false}]) of 
		{ok, Sock} ->
			send_nd_recv(Sock, 1, 0, N);
		Other ->
			io:format("Can't Connect to server : ~p, from ~p~n", [Other, N])
	end.

multiply_data(Data, 0, Result)
	-> Result;
multiply_data(Data, N, Result) ->
	NewResult = concat_binary([Data, Result]),
	NewN = N-1,
	multiply_data(Data, NewN, NewResult).

send_nd_recv(Sock, N, Diff, Sno) ->
	FinalPacket_New = list_to_binary("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx"),
	FinalPack = multiply_data(FinalPacket_New, 10, <<>>),
	FinalPacket = concat_binary([FinalPack,list_to_binary("abcdefghijklmnop")]),
	gen_tcp:send(Sock, FinalPacket),
	{_, Bsec, Busec} = now(),
	case gen_tcp:recv(Sock, 0) of
		{ok, Bin} -> 
			{_, Asec, Ausec} = now(),
			NewDiff =  Diff + ((Asec-Bsec)*1000000 + (Ausec - Busec));
		{error, Reason} ->
			NewDiff =  0,
			io:format("Error ~p~n",[Reason])
	end,
	if N =:= 1000 -> 
			send_nd_recv(Sock, 1, 0, Sno);
	   N =/= 1000 ->
		send_nd_recv(Sock, N+1, NewDiff, Sno)
	end.

