% ------------------------------------------------------------------------------------------------------
% Demonstrates the ECA runtime with a simple alarm clock
% Illustrates the use of variables and a cut in the postcondition
% Uses the \ContractLog\ecaruntime.prova implementation of the ContractLog framework
% ------------------------------------------------------------------------------------------------------

:-eval(consult('ContractLog/math.prova')).
:-eval(consult('ContractLog/list.prova')).
:-eval(consult('ContractLog/list_math.prova')).
:-eval(consult('ContractLog/datetime.prova')).
:-eval(consult('ContractLog/timeinterval.prova')).
:-eval(consult('ContractLog/ecaruntime.prova')).
:-eval(consult('ContractLog/utils.prova')).


%-----------------------------------------------------------------------
% Facts
%-----------------------------------------------------------------------

name(event1(1)).
name("event2").
name("event3").
name(1).

%-----------------------------------------------------------------------
% Define ECA rules
%-----------------------------------------------------------------------

% +++++++++++++++  ECA alarm clock: Start alarm every minute ++++++++++++++
% Only the first successfull variable binding is use, because of the cut in the postconditon
%ECA 1

eca(every5Sec(DT),event(Name),testCondition(),startAction(DT,Name),!,elseAction()). % ECA rule definition

%TIME
every5Sec(DT) :-	
	sysTime(DT),
	interval(timespan(0,0,0,5), DT).

%EVENT empty
event(Name):-
	name(Name).

%CONDITION
testCondition().

%ACTION
startAction(DT,Name) :-
	sysTime(DT2),
	datetime_epoch(DT,Epoch1),
	datetime_epoch(DT2,Epoch2),
	math_sub(Epoch2,Epoch1,Result),
	println(["Execution time: ",Epoch1,Epoch2]),
	println(["Fired action at time ",DT," because of event ",Name]).
	
%ELSE
elseAction() :-
	println(["Else Action"]).


%-----------------------------------------------------------------------
% Start the ECA runtime
%-----------------------------------------------------------------------

start():-
	hideTimer(), % hide the timer
	startECARuntime(".\examples\function_tests\eca_runtime\ecaCut.prova").
	
:- solve(start()).
	