-module(server).

-export([start/0, stop/0]). %% Server interface
-export([init/0, loop/1]). %% Server callbacks

-define(Name, job_server).

%%%%%%%% Server interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
start() ->
    register(?Name, spawn_link(?MODULE, init, [])).

stop() ->
    ?Name ! stop.

%%%%%%%% Server implementation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init()->
    process_flag(trap_exit, true),
    ?MODULE:loop([]).

loop(State)->
    receive
        stop ->
            ok;
        {connect, Cli} -> 
            ?MODULE:loop([Cli|State]);
        {diconnect, Cli} ->
            ?MODULE:loop(lists:filter(fun(A) -> A /= Cli end, State));
        {do, Mod, Fun, Tab} ->
            handle_job(Mod, Fun, Tab),
            ?MODULE:loop(State)
    end.

handle_job(Mod, Fun, Tab) ->
    Data = ets:select(Tab, [{{'$1','$2'},[{'/=', '$1', result}], ['$$']}]),
    Result = Mod:Fun(Data),
    ets:insert(Tab, {result, Result}).
