package senseiTests.performanceGMS;

import sensei.middleware.gms.*;
import sensei.middleware.gmns.*;
import sensei.gmns.*;

import sensei.util.logging.Logger;


public class Stresser extends GroupMemberImpl
{
  class Sender extends Thread
  {
    GroupHandler handler;
    Sender(GroupHandler gh){handler=gh;}
    public void run()
    {
      try
      {
        while(true)
        {
          ++sent;
          handler.castMessage(factory.createMessage());
          sleep(frecuency);
        }
      }
      catch(Exception ex)
      {
        ex.printStackTrace();
        System.exit(0);
      }
    }
  }

  final Factory factory;
  final int frecuency;
  int received, sent;
  Performance performance;

  public Stresser(String name, int n, Factory factory) throws Exception
  {
    this.factory=factory;
    frecuency=n;
    GroupMembershipNamingService service = GroupMembershipNamingServiceFactory.load();
    if (service==null)
    {
      System.out.println("GroupMembershipNamingService is not available");
      System.exit(0);
    }
    else
    {
      Logger.setLogName(name);
      GroupHandlerFactory ghFactory=new GroupHandlerFactoryImpl(theGroupMember()).theGroupHandlerFactory();
      service.findAndJoinGroup("performanceGMS", ghFactory, name, null);
    }
  }
  public void changingView(){}
  public void installView(View parm1){}
  public void processCastMessage(int parm1, Message parm2)
  {
    if ((++received % 2500)==0)
    {
      performance.addMeasure(received);
      System.out.println("received (" + received + ") sent (" + sent + ") msg/second: " + performance.speed()
        + " total: " + performance.totalSpeed());
    }
  }
  public void processPTPMessage(int parm1, Message parm2){}
  public void excludedFromGroup()
  {
    System.out.println("Member excluded from group");
    System.exit(0);
  }
  public void memberAccepted(int parm1, GroupHandler handler, View parm3)
  {
    System.out.println("Member accepted in group");
    performance = new Performance();
    new Sender(handler).start();
  }
}