"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskDetailsPage = void 0;
const test_1 = require("@playwright/test");
function cardinalToOrdinal(numberValue) {
    const realOrderIndex = numberValue.toString();
    if (['11', '12', '13'].includes(realOrderIndex.slice(-2))) {
        return `${realOrderIndex}th`;
    }
    switch (realOrderIndex.slice(-1)) {
        case '1':
            return `${realOrderIndex}st`;
        case '2':
            return `${realOrderIndex}nd`;
        case '3':
            return `${realOrderIndex}rd`;
        default:
            return `${realOrderIndex}th`;
    }
}
class TaskDetailsPage {
    page;
    assignToMeButton;
    completeButton;
    unassignButton;
    assignee;
    completeTaskButton;
    addVariableButton;
    detailsPanel;
    detailsHeader;
    pendingTaskDescription;
    pickATaskHeader;
    emptyTaskMessage;
    nameInput;
    addressInput;
    ageInput;
    variablesTable;
    nameColumnHeader;
    valueColumnHeader;
    form;
    numberInput;
    incrementButton;
    decrementButton;
    dateInput;
    timeInput;
    checkbox;
    selectDropdown;
    tagList;
    detailsInfo;
    textInput;
    assignedToMeText;
    textBox;
    noPreviewContainer;
    previewContainer;
    submitButton;
    constructor(page) {
        this.page = page;
        this.assignToMeButton = page.getByRole('button', { name: 'Assign to me' });
        this.completeButton = page.getByRole('button', { name: 'Complete' });
        this.unassignButton = page.getByRole('button', { name: 'Unassign' });
        this.assignee = page.getByTestId('assignee');
        this.completeTaskButton = page.getByRole('button', { name: 'Complete Task' });
        this.addVariableButton = page.getByRole('button', { name: 'Add Variable' });
        this.detailsPanel = this.page.getByRole('complementary', {
            name: 'Task details right panel',
        });
        this.detailsHeader = page.getByTitle('Task details header');
        this.pendingTaskDescription = page.getByText('Pending task');
        this.pickATaskHeader = page.getByRole('heading', {
            name: 'Pick a task to work on',
        });
        this.emptyTaskMessage = page.getByRole('heading', {
            name: /task has no variables/i,
        });
        this.nameInput = page.getByLabel('Full Name');
        this.addressInput = page.getByLabel('Address*');
        this.ageInput = page.getByLabel('Age');
        this.variablesTable = page.getByTestId('variables-table');
        this.nameColumnHeader = this.variablesTable.getByRole('columnheader', {
            name: 'Name',
        });
        this.valueColumnHeader = this.variablesTable.getByRole('columnheader', {
            name: 'Value',
        });
        this.form = page.getByTestId('embedded-form');
        this.numberInput = this.form.getByLabel('Count');
        this.incrementButton = page.getByRole('button', { name: 'Increment' });
        this.decrementButton = page.getByRole('button', { name: 'Decrement' });
        this.dateInput = page.getByLabel('Date of Birth');
        this.timeInput = page.getByPlaceholder('hh:mm ?m');
        this.checkbox = this.form.getByLabel('Agree');
        this.selectDropdown = this.form.getByText('Select').last();
        this.tagList = page.getByPlaceholder('Search');
        this.detailsInfo = page.getByTestId('details-info');
        this.textInput = page.locator('[class="fjs-input"]');
        this.assignedToMeText = this.page
            .getByTestId('assignee')
            .getByText('Assigned to me');
        this.textBox = this.page.getByLabel('Text Box');
        this.noPreviewContainer = this.page.locator('[class = "fjs-documentPreview-non-preview-item fjs-documentPreview-single-document-container"]');
        this.previewContainer = this.page.locator('[class = "fjs-documentPreview-single-document-container"]');
        this.submitButton = page.getByRole('button', {
            name: 'Submit',
            exact: true,
        });
    }
    async clickAssignToMeButton() {
        await this.assignToMeButton.click({ timeout: 60000 });
        await (0, test_1.expect)(this.page.getByText('Assigning...')).not.toBeVisible({
            timeout: 180000,
        });
        await (0, test_1.expect)(this.assignedToMeText).toBeVisible({
            timeout: 60000,
        });
    }
    async clickUnassignButton() {
        await this.unassignButton.click();
    }
    async clickCompleteTaskButton() {
        await this.completeTaskButton.click({ timeout: 120000 });
    }
    async clickAddVariableButton() {
        await this.addVariableButton.click();
    }
    async replaceExistingVariableValue(values) {
        const { name, value } = values;
        await this.page.getByTitle(name).clear();
        await this.page.getByTitle(name).fill(value);
    }
    getNthVariableNameInput(nth) {
        return this.page.getByRole('textbox', {
            name: `${cardinalToOrdinal(nth)} variable name`,
        });
    }
    getNthVariableValueInput(nth) {
        return this.page.getByRole('textbox', {
            name: `${cardinalToOrdinal(nth)} variable value`,
        });
    }
    async addVariable(payload) {
        const { name, value } = payload;
        this.clickAddVariableButton();
        await this.getNthVariableNameInput(1).fill(name);
        await this.getNthVariableValueInput(1).fill(value);
    }
    async fillNumber(number) {
        await this.numberInput.fill(number);
    }
    async clickIncrementButton() {
        await this.incrementButton.click();
    }
    async clickDecrementButton() {
        await this.decrementButton.click();
    }
    async fillDate(date) {
        await this.dateInput.click();
        await this.dateInput.fill(date);
        await this.dateInput.press('Enter');
    }
    async enterTime(time) {
        await this.timeInput.click();
        await this.page.getByText(time).click();
    }
    async checkCheckbox() {
        await this.checkbox.check();
    }
    async selectDropdownValue(value) {
        await this.selectDropdown.click();
        await this.page.getByText(value).click();
    }
    async clickRadioButton(radioBtnLabel) {
        await this.page.getByText(radioBtnLabel).click();
    }
    async checkChecklistBox(label) {
        await this.page.getByLabel(label).check();
    }
    async enterTwoValuesInTagList(value1, value2) {
        await this.tagList.click();
        await this.page.getByText(value1).click();
        await this.page.getByText(value2, { exact: true }).click();
    }
    async clickTextInput() {
        const maxRetries = 10;
        let attempts = 0;
        while (attempts < maxRetries) {
            try {
                await this.textInput.click({ timeout: 90000 });
                break;
            }
            catch (error) {
                attempts += 1;
                if (attempts < maxRetries) {
                    console.warn(`Attempt ${attempts} failed. Reloading page and retrying...`);
                    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
                    await sleep(10000);
                    await this.page.reload();
                }
                else {
                    throw new Error(`Failed to click text input after ${maxRetries} attempts`);
                }
            }
        }
    }
    async fillTextInput(value) {
        await (0, test_1.expect)(this.textInput).toBeVisible({ timeout: 90000 });
        await this.textInput.click();
        await this.textInput.fill(value, { timeout: 90000 });
        (0, test_1.expect)(await this.textInput.inputValue()).toBe(value);
    }
    async fillTextBox(text) {
        await this.textBox.fill(text);
    }
    async fillName(nameInput) {
        await this.nameInput.fill(nameInput);
    }
    async assertDocumentDownloadButton(documentName) {
        await (0, test_1.expect)(this.page.locator(`button[aria-label="Download ${documentName}"]`)).toBeVisible({ timeout: 60000 });
    }
    async assertLoadedImage(documentName) {
        await (0, test_1.expect)(this.page.locator(`img[alt="${documentName}"]`)).toBeVisible({
            timeout: 120000,
        });
    }
    async assertPdfPreviewViewerExists() {
        const containers = this.page.locator('[class="fjs-documentPreview-single-document-container"]');
        const firstPdfViewer = containers
            .first()
            .locator('.fjs-documentPreview-pdf-viewer');
        const lastPdfViewer = containers
            .last()
            .locator('.fjs-documentPreview-pdf-viewer');
        // The PDF viewer can take longer to mount on AWS clusters; if the first
        // wait misses, reload once and give the second wait more headroom before
        // failing the test.
        try {
            await (0, test_1.expect)(firstPdfViewer.or(lastPdfViewer)).toBeVisible({
                timeout: 60000,
            });
        }
        catch {
            await this.page.reload();
            await (0, test_1.expect)(firstPdfViewer.or(lastPdfViewer)).toBeVisible({
                timeout: 90000,
            });
        }
    }
    async clickSubmitButton() {
        await (0, test_1.expect)(this.submitButton).toBeVisible();
        await (0, test_1.expect)(this.submitButton).toBeEnabled();
        await this.submitButton.click();
    }
}
exports.TaskDetailsPage = TaskDetailsPage;
