% Since Prova 2.0
% Demonstrate
% - Parallel partitions in in-body reactions

:- eval(server()).

:- eval(client()).

%%%%%%%%%%%%%%%%%%
%%%%% SERVER %%%%%
%%%%%%%%%%%%%%%%%%

server() :-
	println(["==========ex062=========="]),
	rcvMult(XID,Protocol,From,request,loan(UserID),Msg),
	println(["[",XID,"] ",Msg," Received new loan request for user: ",UserID]),
	unique_id(PID1),
	unique_id(PID2),
	branches(XID,UserID,[PID1,PID2]).

credit_limit('user001',1000).
credit_limit('user002',3000).

authorize_loan(UserID,Amount) :-
	println(["Condition authorize_loan being tested."]),
	credit_limit(UserID,Limit),
	Limit>=Amount.

branches(XID,UserID,[PID1,PID2]) :-
	rcvMsgP([PID1],[],rcvMsg(XID,Protocol,From,data,amount(Amount)),condition(authorize_loan(UserID,Amount))),
	println(["[",XID,"] Loan for ",Amount," authorized for user: ",UserID]).
branches(XID,UserID,[PID1,PID2]) :-
	rcvMsgP([PID2],[PID1],rcvMsg(XID,Protocol,From,cancel,request())),
	println(["[",XID,"] Loan request cancelled for user: ",UserID]).

%%%%%%%%%%%%%%%%%%
%%%%% CLIENT %%%%%
%%%%%%%%%%%%%%%%%%

client() :-
	iam(Me),
	sendMsg(XID,self,Me,request,loan('user001'),"Test 1:"),
	sendMsg(XID,self,Me,cancel,request()),
	sendMsg(XID,self,Me,data,amount(900)),
	println(["Started first conversation: ",XID]).
client() :-
	iam(Me),
	sendMsg(XID,self,Me,request,loan('user001'),"Test 2:"),
	sendMsg(XID,self,Me,data,amount(900)),
	sendMsg(XID,self,Me,cancel,request()),
	println(["Started second conversation: ",XID]).
client() :-
	iam(Me),
	sendMsg(XID,self,Me,request,loan('user002'),"Test 3:"),
	sendMsg(XID,self,Me,data,amount(2000)),
	sendMsg(XID,self,Me,cancel,request()),
	println(["Started third conversation: ",XID]).
