import { setPRNG } from "./nacl-fast.js";

/**
 * This only be used when taler util is packaged to run in browser
 * but run in non-browser environment which is common for
 * unit testing. Under this conditions no random is ok.
 */
const nullRandom = {
  getRandomValues: (c: Uint8Array<ArrayBuffer>) => c,
};

export function loadBrowserPrng() {
  // Initialize PRNG if environment provides CSPRNG.
  // If not, methods calling randombytes will throw.
  // @ts-expect-error self is not defined
  const cr = typeof self !== "undefined" ? self.crypto || self.msCrypto : nullRandom;

  const QUOTA = 65536;
  setPRNG(function (x: Uint8Array, n: number) {
    let i;
    const v = new Uint8Array(n);
    for (i = 0; i < n; i += QUOTA) {
      cr.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
    }
    for (i = 0; i < n; i++) x[i] = v[i];
    for (i = 0; i < v.length; i++) v[i] = 0;
  });
}
