-module(dispatcher).
-export([start/0, init/0, handle/2]).
start() ->
code:purge(server),
code:load_abs("../common/server"),
case server:start(dis, dispatcher) of
true ->
io:format("Server started... ~n"),
true;
_ ->
io:format("Error starting server! Exiting.~n"),
exit(1)
end.
init() ->
dict:new().
handle({register, {User, Password}}, Dict) ->
case dict:find(User, Dict) of
{ok, _}->
{{error, duplicated_user}, Dict};
_ ->
io:format("User created: ~s~n", [User]),
{{ok, user_created}, dict:store(User, Password, Dict)}
end;
handle({login, {Node, User, Password}}, Dict) ->
case dict:find(User, Dict) of
{ok, Password} ->
case client:start(Node) of
{ok, Pid} ->
{{ok, {logged_in, Pid}}, Dict};
_ ->
{{error, unable_to_login}, Dict}
end;
_ ->
{{error, user_or_password_invalid}, Dict}
end;
handle({'EXIT', _, _}, Dict) ->
Dict;
handle(_, Dict) ->
{{error, unknown_command}, Dict}.