-module(echoserv).
-export([dispatcher/2, handler/1, start_server/0,find_load/3]).
-define(PORT, 1500).

find_load(Sno, N, {_, Sec, _}) ->
	receive
		{recv_pkt} ->
			{_, NewSec, _} = now(),
			Diff = NewSec - Sec,
			if 
				Diff =:= 60 ->
					io:format("~p : ~p~n",[Sno, N]),
					NewN=0,
					NewSno = Sno + 1,
					Time = {0,NewSec,0};
				Diff =/= 60 ->
					NewN = N+1,
					Time = {0,Sec,0},
					NewSno = Sno
					
			end
	end,
	find_load(NewSno, NewN, Time).

dispatcher(Lsocket, Accept_count) ->
	io:format("Accept_count = ~B ~n",[Accept_count]),
	case gen_tcp:accept(Lsocket) of
		{ok, LS} -> spawn(echoserv, handler, [LS]),
			dispatcher(Lsocket, Accept_count + 1);
		Other ->
			io:format("Can't accept socket ~p Accept Count ~B~n", [Other, Accept_count])
	end.

handler(LS) ->
	case gen_tcp:recv(LS, 0) of
		{ok, B} -> gen_tcp:send(LS, B),
			findload ! {recv_pkt},
			handler(LS);
		Other ->
			io:format("Can't recv socket ~p~n", [Other]),
			gen_tcp:close(LS)
	end.

start_server() ->
	register(findload,spawn(echoserv,find_load,[1, 0,now()])),
	case gen_tcp:listen(?PORT , [binary, {reuseaddr, true}, {packet, 0},
					{active, false}, {backlog, 500}]) of
		{ok, Lsock} ->
			spawn(echoserv, dispatcher, [Lsock, 0]);
		Other ->
			io:format("Can't listen to socket ~p~n", [Other])
	end.
