package senseiTests.concurrency;

import sensei.domains.*;
import sensei.middleware.domains.*;
import sensei.middleware.gms.GroupMember;
import sensei.util.Error;

import java.util.Map;

class DynamicCreator extends DynamicSubgroupsUserBaseImpl
{
  public DynamicCreator(DomainGroupHandler groupHandler, Map monitors, Printer printer) throws Exception
  {
    this.groupHandler=groupHandler;
    this.monitors=monitors;
    this.printer=printer;
  }
  public void subgroupRemoved(int remover, int id, DynamicSubgroupInfo member)
  {
    String memberName = ((DynamicSubgroupInfoAsString)member).info;
    printer.print("Deleted monitor with id "+id + ", from member " +memberName);
    monitors.remove(new Integer(id));
  }

  public GroupMember subgroupCreated(int creator, int id, DynamicSubgroupInfo member)
  {
    String memberName = ((DynamicSubgroupInfoAsString)member).info;
    printer.print("New monitor created with id "+id + ", originated in member " +memberName);
    GroupMonitor impl = null;
    try
    {
      impl=new GroupMonitorImpl(id, groupHandler).theGroupMonitor();
      monitors.put(new Integer(id), impl);
      impl.assumeState();
    }
    catch(Exception ex)
    {
      Error.unhandledException("TestMonitor", ex);
    }
    return impl;
  }

  public GroupMember acceptSubgroup(int id, DynamicSubgroupInfo member)
  {
    String memberName = ((DynamicSubgroupInfoAsString)member).info;
    printer.print("Additional monitor created with id "+id + ", originated in member " +memberName);
    GroupMonitor impl = null;
    try
    {
      impl=new GroupMonitorImpl(id, groupHandler).theGroupMonitor();
      monitors.put(new Integer(id), impl);
    }
    catch(Exception ex)
    {
      Error.unhandledException("TestMonitor", ex);
    }
    return impl;
  }

  DomainGroupHandler groupHandler;
  Map monitors;
  Printer printer;
}