package senseiTests.randomCounter.corba;

import java.util.BitSet;
import java.util.Random;

/**
  *  Class implementing a set of numbers
  */
class SetNumbers
{

  public int getRandom()
  {
    return random.nextInt(MAX_NUMBERS);
  }

  /**
    *  Returns the first free number after the number specified
    *  as parameter. If there are none free, it just clears the
    *  content, giving again the same numbers
    */
  public int getFreeNumber(int seed)
  {
    if (seed>MAX_NUMBERS) seed=0; //not a great check!
    for (int i=seed;i<MAX_NUMBERS;i++)
    {
      if (setFreeNumber(i))
      {
        return i;
      }
    }
    for (int i=0;i<seed;i++)
    {
      if (setFreeNumber(i))
      {
        return i;
      }
    }
    System.out.println("SET is full, clearing it ...");
    set.clear();
    return getFreeNumber(seed);
  }

  boolean setFreeNumber(int pos)
  {
    if (set.get(pos))
    {
      return false;
    }
    set.set(pos);
    return true;
  }

  BitSet set = new BitSet(MAX_NUMBERS);
  Random random = new Random();

  static int MAX_NUMBERS=5;
  static
  {
    System.out.println("Sets use up to " + MAX_NUMBERS + " numbers");
    if (MAX_NUMBERS<1)
    {
      System.err.println("The set cannot be empty!!");
      System.exit(0);
    }
  }
}