const { sha256 } = require('./hash');

function seedToInt(seed) {
  return Number(BigInt(`0x${sha256(seed).slice(2, 18)}`) % BigInt(Number.MAX_SAFE_INTEGER));
}

class Rng {
  constructor(seed) {
    this.state = seedToInt(seed) || 1;
  }

  next() {
    this.state = (this.state * 48271) % 0x7fffffff;
    return this.state / 0x7fffffff;
  }

  int(min, max) {
    return min + Math.floor(this.next() * (max - min + 1));
  }

  pick(items) {
    return items[this.int(0, items.length - 1)];
  }

  nonZero(min, max) {
    let value = 0;
    while (value === 0) {
      value = this.int(min, max);
    }
    return value;
  }
}

module.exports = { Rng };
