import { floor } from './math.js';
import { BITS21, BITS32 } from './binary.js';
import { getRandomValues } from './webcrypto.js';

/**
 * Isomorphic module for true random numbers / buffers / uuids.
 *
 * Attention: falls back to Math.random if the browser does not support crypto.
 *
 * @module random
 */


const rand = Math.random;

const uint32 = () => getRandomValues(new Uint32Array(1))[0];

const uint53 = () => {
  const arr = getRandomValues(new Uint32Array(8));
  return (arr[0] & BITS21) * (BITS32 + 1) + (arr[1] >>> 0)
};

/**
 * @template T
 * @param {Array<T>} arr
 * @return {T}
 */
const oneOf = arr => arr[floor(rand() * arr.length)];

// @ts-ignore
const uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11;

/**
 * @return {string}
 */
const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>
  (c ^ uint32() & 15 >> c / 4).toString(16)
);

export { oneOf, rand, uint32, uint53, uuidv4 };
