package nxm.sys.intr;

import java.security.SecureRandom;

import nxm.sys.lib.Intrinsic;
import nxm.sys.libm.Random;

/** Set random number generator seed.
    See {@link Random} and {@link Random#setSeed(int)}
    @author Neon Ngo
    @since NeXtMidas 3.1.1
*/
public class Setseed extends Intrinsic {

  /** maximum seed value = 2**26 */
  private static final int MAX_SEED_VALUE = 67108864;

  /** default constructor */
  public Setseed () {}

  public int process () {

    int newseed;
    boolean genseed = MA.getState("/GEN", false);
    if (genseed) {
      SecureRandom secureRand = new SecureRandom();
      newseed = secureRand.nextInt(MAX_SEED_VALUE);
    }
    else {
      newseed = MA.getL("NEWSEED", -1);
    }

    if (newseed >= MAX_SEED_VALUE) M.error("Seed value ["+newseed+"] exceeds 2**26 - 1");
    if (newseed >= 0) Random.setSeed(newseed); // negative is ignored (aka noop)

    if (verbose) {
      M.info("Seed is "+ Random.getSeed());
    }

    return FINISH;
  }

}
