-module(bank_server). -behaviour(gen_server). -define(SERVER, ?MODULE). %% API -export([start_link/0, create_account/1, balance/1, deposit/2, withdrawal/2, stop/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %%==================================================================== %% API %%==================================================================== start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). create_account(ClientName) -> gen_server:cast(?SERVER, {create_account, ClientName}). balance(ClientName) -> gen_server:call(?SERVER, {get_balance, ClientName}). deposit(ClientName, Amount) -> gen_server:call(?SERVER, {deposit, ClientName, Amount}). withdrawal(ClientName, Amount) -> gen_server:call(?SERVER, {withdrawal, ClientName, Amount}). stop() -> gen_server:cast(?SERVER, stop). %%==================================================================== %% gen_server callbacks %%==================================================================== init([]) -> {ok, dict:new()}. handle_call({get_balance, ClientName}, _From, State) -> case dict:find(ClientName, State) of {ok, Balance} -> {reply, Balance, State}; error -> io:format("Error. Account not registered.", []), {reply, no_account, State} end; handle_call({deposit, ClientName, Amount}, _From, State) -> case dict:find(ClientName, State) of {ok, Balance} -> NewBalance = Balance + Amount, {reply, NewBalance, dict:store(ClientName, NewBalance, State)}; error -> {reply, no_account, State} end; handle_call({withdrawal, ClientName, Amount}, _From, State) -> case dict:find(ClientName, State) of {ok, Balance} -> NewBalance = Balance - Amount, {reply, NewBalance, dict:store(ClientName, NewBalance, State)}; error -> {reply, no_account, State} end; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast({create_account, ClientName}, State) -> case dict:find(ClientName, State) of {ok, _} -> io:format("The Account is already registered.", []), {noreply, State}; error -> {noreply, dict:store(ClientName, 0, State)} end; handle_cast(stop, State) -> {stop, normal, State}; handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.