package senseiTests.domainsTest;

import sensei.middleware.gms.*;
import sensei.middleware.domains.*;
import senseiTests.middleware.domainsTest.AddColourMessage;
import senseiTests.middleware.domainsTest.RemColourMessage;
import senseiTests.middleware.domainsTest.ColourPhaseCoordination;
import senseiTests.middleware.domainsTest.ColourState;
import senseiTests.middleware.domainsTest.Factory;

class ColoursSubgroupNoST extends GroupMemberImpl implements ColoursSubgroup
{
  public ColoursSubgroupNoST(DomainGroupHandler groupHandler, ColoursSubgroupUser user,
      Factory factory, StateTransferAnswerer answerer) throws Exception
  {
    this.user=user;
    this.answerer=answerer;
    this.factory=factory;
    state=new StateKeeper();
    this.groupHandler=groupHandler;
  }

  public void setIdentity(int identity)
  {
//    if (id==0)
//    {
//      state.generateRandomState();
//      answerer.onAssumeState(this);
//      user.changedState(identity, state.toString());
//    }
    id=identity;
  }

  public void setState(String substates[])
  {
    state.setState(substates);
    user.changedState(id, state.toString());
  }

  public String getAColour()
  {
    return state.generateRandomSubState();
  }

  public void addColour(String colour) throws Exception
  {
    groupHandler.syncCastDomainMessage(factory.createAddColourMessage(id,colour), true);
  }

  public void remColour() throws Exception
  {
    groupHandler.syncCastDomainMessage(factory.createRemColourMessage(id), true);
  }

  public int getId()
  {
    return id;
  }

  public String getColour(int pos)
  {
    return state.getSubState(pos);
  }

  public void regenerateState()
  {
    state.generateRandomState();
    user.changedState(id, state.toString());
  }

  public void processPTPMessage(int sender, Message msg)
  {
    System.out.println("processPTPMessage");
  }

  public void processCastMessage(int sender, Message msg)
  {
    boolean ok;
    if (msg instanceof AddColourMessage)
    {
      AddColourMessage message = (AddColourMessage) msg;
      state.addSubState(message.colour);
      ok=true;
    }
    else if (msg instanceof RemColourMessage)
      ok = state.removeSubState();
    else
      ok=false;
    if (ok)
      user.changedState(id, state.toString());
  }

  public void memberAccepted(int identity, GroupHandler handler, View theView)
  {
    this.groupHandler = (DomainGroupHandler) (handler);
  }
  public void changingView()
  {
  }
  public void installView(View theView)
  {
  }
  public void excludedFromGroup()
  {
  }

  StateKeeper state;
  boolean onTransfer;
  int id;

  DomainGroupHandler groupHandler;
  ColoursSubgroupUser user;
  StateTransferAnswerer answerer;
  Factory factory;
};