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

test('export module', async ({ page, context }) => {
  // Override with environment variables, if they exist
  const username = process.env.ELIXFORMS_USERNAME || null;
  const password = process.env.ELIXFORMS_PASSWORD || null;
  const moduleTag = process.env.ELIXFORMS_MODULE_TAG || null;
  // Validate that all required environment variables are set
  if (!username || !password || !moduleTag) {
    throw new Error('Please set ELIXFORMS_USERNAME, ELIXFORMS_PASSWORD, and ELIXFORMS_MODULE_TAG using one of:\n- an .env file in the project root\n- specify an .env file with `npx env-cmd --file <.env_path> -- <command>`\n- pass them as environment variables');
  }

  test.setTimeout(60_000); // Set a longer timeout for this test

  await page.goto('https://console-unipr.elixforms.it/backoffice/');

  let loginButton = page.getByRole('button', { name: 'Accedi' });
  await expect(loginButton).toBeVisible();

  // Write username and password
  await page.locator('#username').fill(username);
  await page.locator('#password').fill(password);
  // Click login button
  await loginButton.click();

  await expect(page.getByText('Benvenuto')).toBeVisible();

  await page.goto('https://console-unipr.elixforms.it/rwe2/admin_console.jsp');

  let moduleSearchTextbox = page.locator('#TITLE__TAG__CATTAG');
  await expect(moduleSearchTextbox).toBeVisible();
  await moduleSearchTextbox.clear();
  await moduleSearchTextbox.fill(moduleTag);
  await moduleSearchTextbox.press('Enter');

  await page.waitForTimeout(2000);

  let firstResultButton = page
    .locator('//div[contains(@class, "item")][1]//input[starts-with(@name, "INSERT_BTN_USER_")]');
  await expect(firstResultButton).toBeVisible();

  await firstResultButton.click();

  // Start waiting for new page before clicking. Note no await.
  const pagePromise = context.waitForEvent('page');

  let exportLink = page.getByText('Esporta il modulo');
  await expect(exportLink).toBeVisible();
  await exportLink.click();

  const newPage = await pagePromise; // Wait for the new page to open.
  await newPage.waitForLoadState();
  await newPage.bringToFront();

  let moduleProtocolCheckbox = newPage.locator('#moduleProtocol');
  await expect(moduleProtocolCheckbox).toBeVisible();
  await moduleProtocolCheckbox.click();

  let downloadButton = newPage.locator('#download');
  await expect(downloadButton).toBeVisible();
  await downloadButton.click();

  await page.waitForTimeout(5000);

  let downloadLink = newPage.getByRole('link', { name: 'Scarica il modulo' });
  await expect(downloadLink).toBeVisible();
  
  // Start waiting for download before clicking. Note no await.
  const downloadPromise = newPage.waitForEvent('download');
  await downloadLink.click();
  const download = await downloadPromise;

  // Wait for the download process to complete and save the downloaded file somewhere.
  await download.saveAs('./downloads/' + download.suggestedFilename());
});
