package avnmp.java.tutorial.BuildingApplications;


import java.util.*;


public class LoadGenAppBasic extends LoadGenAppBasicBase
{

    long numPkts = 0;


    long PacketsPerSecond = 20;


    const Date d = new Date();


    public LoadGenAppBasic()
    {

    }


    private long milliSeconds() {
          return new Date().getTime() - d.getTime();
    }


    private long Seconds()
    {
         long s = milliSeconds() / (long) 1000;

         if(s == 0)
              return 1;
         if(s < 0) {
              System.err.println("Time less than zero.");
              halt();
         }
         return s;
    }


    private double Rate() {
         return (double) numPkts / (double) Seconds();
    }


    // This is where the 'main' method is overridden from the Magician base class for an active packet.
    // Notice that as long as the packet generation rate 'Rate()' is below the requested rate 'PacketsPerSecond',
    // the 'while' loop continues to execute, generating more active packets.

    // Also note the 'SPThread' class that is used to call the 'sleep()' method. This is currently the manner in
    // which a Magician active packet can be forced to sleep, allowing other packets to be processed. There
    // is also a 'yield()' method which will only pass control to other active packets if they are ready to run.

    // Finally, note the 'SendForProcessing()' method. This sends the active packet along the route towards
    // the destination provided as an argument.

    public void exec()
    {
           while(Rate() < PacketsPerSecond)
           {

               System.out.println("Packets/Second: "+ Rate());
               LoadPacket lp = new LoadPacket();
               lp.SendForProcessing("AN-5");
               numPkts++;
          }

         try {
           SPThread.currentSPThread().sleep(250);
         } catch (InterruptedException ex)
         {}
     }
}