
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Given an external event, trigger all relevant processes. 
% 
% Note: in the current implementation, a process may or may not 
%       have a trigger. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

add_process_to_agenda(E) :-
    
  E = dyn(event(Instance, Event, EStatus, Priority, 
          _/End_time, 
          (Provider/Provider_type, Receiver/Receiver_type), 
          Event_content)), 

  EStatus = New_status/IDlist, 

  %%%%%%%%%%%%%%%%%% match process %%%%%%%%%%%%%%%
  process(Instance, Process/PID, PStatus, Priority, 
          Begin_time/End_time, Time_cost, 
          (Provider/Provider_type, Receiver/Receiver_type), 
          P_Trigger, Precond, Action, Postcond), 

    ( P_Trigger = true; P_Trigger = [D] ), 

  P = process(Instance, Process/PID, PStatus, Priority, 
              Begin_time/End_time, Time_cost, 
              (Provider/Provider_type, Receiver/Receiver_type), 
              P_Trigger, Precond, Action, Postcond), 

  %%% match junctions: if it is followed by a start junction, or 
  %%%                  if it is followed by a control-link, or 
  %%%                  if it is followed by an and-joint junction, or 
  %%%                  if it is followed by an and-split junction, or 
  %%%                  if it is followed by an or-joint junction, or 
  %%%                  if it is followed by an or-split junction, 
  %%% and it fits the process, add it to the agenda

    ( EStatus = received/[], start[PID];
      EStatus = processed/List, control_link(A, PID), 
      member(A, List);

      EStatus = processed/List, and_split(A, Blist), 
      member(A, List), member(PID, Blist);
      EStatus = processed/List, or_split(A, Blist), 
      member(A, List), member(PID, Blist);
      
      EStatus = processed/List, and_joint(Alist, PID), 
      subset(Alist, List); 
      EStatus = processed/List, or_joint(Alist, PID), 
      member(X, List), member(X, Alist); )

      %%% update process time, and 
      %%% add process to process agenda 

      dyn(current_time(Time)), 
      Begin_time = Time, 
      End_time is Time + Time_cost,
      assert(dyn(agenda(P))),

      %% update the event status to "processed", to indicated that it is 
      %% being processed. 

      retract(E),
      New_status = processed,       
      assert(E), 

      add_process_to_agenda(T).

add_process_to_agenda(_). 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



