const { Builder, Browser, By, until } = require('selenium-webdriver');
const { Options } = require('selenium-webdriver/chrome');
const path = require('path');

(async function exportElixFormsModule() {
    // Override with environment variables, if they exist
    const username = process.env.ELIXFORMS_USERNAME || null;
    const password = process.env.ELIXFORMS_PASSWORD || null;
    const moduleName = process.env.ELIXFORMS_MODULE_TAG || null;
    // Validate that all required environment variables are set
    if (!username || !password || !moduleName) {
        console.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');
        process.exit(1);
    }

    const downloadDir = path.resolve(__dirname, 'downloads');

    // Configure Chrome options
    let options = new Options();
    options.setUserPreferences({
        'download.default_directory': downloadDir, // Set download folder
        'download.prompt_for_download': false,     // No prompt
        'download.directory_upgrade': true,
        'safebrowsing.enabled': true               // Avoid blocking
    });

    let driver = await new Builder()
        .forBrowser(Browser.CHROME)
        .setChromeOptions(options)
        .build();

    const originalWindow = await driver.getWindowHandle();

    // Implicit timeouts
    await driver.manage().setTimeouts({ implicit: 3000 });

    await driver.get('https://console-unipr.elixforms.it/backoffice/');

    await driver
        .findElement(By.id('username'))
        .sendKeys(username); // 'Automation_User'

    await driver
        .findElement(By.id('password'))
        .sendKeys(password); // 'n_HH9shL#VPeiiT^%;:t5/,jY'

    await driver
        .findElement(By.name('INSERT_BTN00000'))
        .click();

    // Wait for "Benvenuto" (quit if not found, likely login failed)
    await driver
        .wait(until.elementLocated(By.id('title_0')), 10000)
        .catch(() => {
            console.error('Login failed or "Benvenuto" not found');
            driver.quit();
            process.exit(1);
        });

    await driver
        .navigate()
        .to('https://console-unipr.elixforms.it/rwe2/admin_console.jsp');

    let moduleSearchTextbox = await driver.findElement(By.id('TITLE__TAG__CATTAG'));
    await moduleSearchTextbox.clear();
    await moduleSearchTextbox.sendKeys(moduleName);
    await moduleSearchTextbox.sendKeys('\n');

    // Needed to wait for the search results to load before clicking the export button
    await driver.sleep(2000);

    await driver
        .findElement(By.xpath('//div[contains(@class, "item")][1]'))
        .findElement(By.xpath('.//input[starts-with(@name, "INSERT_BTN_USER_")]'))
        .click()

    await driver
        .findElement(By.linkText('Esporta il modulo'))
        .click();

    // Wait for the new tab to open and switch to it
    await driver.wait(async () => (await driver.getAllWindowHandles()).length === 2, 5000);
    const windows = await driver.getAllWindowHandles();
    windows.forEach(async handle => {
        if (handle !== originalWindow) {
            await driver.switchTo().window(handle);
        }
    });

    // Wait for the new tab to finish loading content
    let moduleProtocol = await driver.findElement(By.id('moduleProtocol'));
    if (!await moduleProtocol.isSelected()) {
        await moduleProtocol.click();
    }

    await driver
        .findElement(By.id('download'))
        .click();

    let downloadLink = await driver.wait(until.elementLocated(By.linkText('Scarica il modulo')));
    let href = await downloadLink.getAttribute('href');
    downloadLink.click();

    // Wait for the download to complete (this is a simple approach, adjust as needed)
    await driver.sleep(5000);

    await driver.quit();
})();
