/*
 *  Wake up element after some data are sent to it services class
 *
 *  2004 - 2011 Frantisek Zboril jr.
 *  Faculty of Information Technology
 *  zborilf@fit.vutbr.cz
 *  http://www.fit.vutbr.cz/~zborilf
 *
 * (C) Brno University of Technology
 * Freeware licence VUT v Brně
 * https://wis.fit.vutbr.cz/FIT/db/dir.php/dr/VZ2007/externiInformace/softwareNaWebu/Priloha2_rozh23.pdf

 */

package jTMass.core.jTMassPlatform.jTServices;

import jTMass.TMass;
import jTMass.core.jALLL.jTObjects.TFail;
import jTMass.core.jALLL.jTObjects.TList;
import jTMass.core.jALLL.jTObjects.TObject;
import jTMass.core.jTMassModel.TModelConnection;
import jTMass.core.jTMassPlatform.TPlatform;

public class TSWaitMessage extends TASBlockingService{

    Long PDelay=new Long(1);
    Long PTimeLimit;

    boolean messageAtGate(){
        TModelConnection con=
            PPlatform.getConnectionToElementName(PClient);
        if(con!=null)
            if(con.dataPresent()){
                return(true);
            }
        return(false);
    }

    @Override
    public boolean reviveService(){
         if(messageAtGate()||(PTimeLimit<TMass.getSimulator().getModelTime())){
            PPlatform.runandSet(PClient,null);
            return(finished());
        }
         else
            this.generateReviveEvent(PDelay);

         return(true);
    }

    @Override
    public TObject processService(TList parameters, String clientName, String serviceName) {
        super.processService(parameters, clientName, serviceName);
        try{
            PTimeLimit=TMass.getSimulator().getModelTime()+
                    Integer.valueOf(parameters.get(0).getContent());
        }catch(Exception e){
            TMass._Terminal.reportError("Wronag 'wait message' time limit");
            return(new TFail());
        }
            PNextTime=new Long(0);
            PClient=clientName;
            PPlatform.storeActiveService(this);
            reviveService();
            return(null);
    }

    public TSWaitMessage(TPlatform platform){
        super(platform);
    }
}