import { test, expect } from '@playwright/test';
import { importUser } from './testUtils';

// Function to generate a random string of specified length
function generateRandomString(length) {
  return Math.random().toString(36).substring(2, 2 + length);
}

// Function to create an array of unique strings
function createUniqueStringsArray(count) {
  const stringsArray = [];
  const stringLength = 16;

  for (let i = 0; i < count; i++) {
    let randomString = generateRandomString(stringLength);
    stringsArray.push(randomString);
  }

  return stringsArray;
}

// Function to create an array of two-digit non-zero numbers
function createRandomNumbersArray(count) {
  const numbersArray = [];

  for (let i = 0; i < count; i++) {
    let randomNumber = Math.floor(Math.random() * 99) + 1;
    numbersArray.push(randomNumber);
  }

  return numbersArray;
}

test('Record 10 new gifts', async ({ page }) => {
  test.slow(); // Extend the test timeout
  const giftCount = 10;

  // Standard text
  const standardTitle = "Gift ";

  // Field value arrays
  const finalTitles = [];
  const finalNumbers = [];

  // Create arrays for field input
  const uniqueStrings = createUniqueStringsArray(giftCount);
  const randomNumbers = createRandomNumbersArray(giftCount);

  // Populate array with titles
  for (let i = 0; i < giftCount; i++) {
    let loopTitle = standardTitle + uniqueStrings[i];
    finalTitles.push(loopTitle);
    let loopNumber = randomNumbers[i];
    finalNumbers.push(loopNumber);
  }

  // Import user 00
  await importUser(page, '00');

  // Pause a bit
  await page.waitForTimeout(3000); // I have to wait, otherwise the (+) button to add a new project doesn't appear

  // Record new gifts
  for (let i = 0; i < giftCount; i++) {
    // Record something given
    await page.goto('./');
    await page.getByRole('heading', { name: 'Unnamed/Unknown' }).click();
    await page.getByPlaceholder('What was given').fill(finalTitles[i]);
    await page.getByRole('spinbutton').fill(finalNumbers[i].toString());
    await page.getByRole('button', { name: 'Sign & Send' }).click();
    await expect(page.getByText('That gift was recorded.')).toBeVisible();

    // Refresh home view and check gift
    await page.goto('./');
    await expect(page.locator('li').filter({ hasText: finalTitles[i] })).toBeVisible();
  }
});