/**
 * Class for generating random and pseudo random things.
 */
export class RandomGenerator {
  /**
   * Generate a pseudo random string of a defined length. Will always start with `a..z`. For use as random element IDs
   * @param number length The number of chars in the
   * @returns random string
   *
   * @see https://react.dev/reference/react/useId for a different use case
   */
  public randomString(length: number = 8): string {
    if (length < 1) throw new Error("Length must be at least 1");

    const letters = "abcdefghijklmnopqrstuvwxyz";
    const chars =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    // First char: lowercase letter
    let result = letters.charAt(Math.floor(Math.random() * letters.length));

    // Remaining chars: full set
    for (let i = 1; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }

    return result;
  }
}

let randomGeneratorInstance: RandomGenerator | null = null;

/**
 * Hook for generating random and pseudo random data
 */
export default function useRandom(): RandomGenerator {
  if (!randomGeneratorInstance) {
    randomGeneratorInstance = new RandomGenerator();
  }
  return randomGeneratorInstance;
}
