"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlayPage = void 0;
const test_1 = require("@playwright/test");
const sleep_1 = require("../../utils/sleep");
const expectLocatorWithRetry_1 = require("../../utils/assertionHelpers/expectLocatorWithRetry");
const maxWaitTimeSeconds = 180000;
class PlayPage {
    page;
    completeJobButton;
    saveScenarioButton;
    viewScenarioButton;
    runAllScenariosButton;
    confirmSaveScenarioButton;
    enterScenarioNameInput;
    confirmDeleteScenarioButton;
    viewAllScenariosButton;
    getScenarioRowByName;
    getScenarioRow;
    diagram;
    startInstanceButton;
    startInstanceWithCachedButton;
    notifications;
    saveScenarioModal;
    loadingInstanceDetailsText;
    retryButton;
    dialog;
    constructor(page) {
        this.page = page;
        this.dialog = page.getByRole('dialog');
        this.completeJobButton = page
            .getByTestId('diagram')
            .getByLabel('Complete job');
        this.saveScenarioButton = page.getByRole('button', { name: 'Save scenario' });
        this.viewScenarioButton = page.getByRole('button', { name: 'View scenario' });
        this.runAllScenariosButton = page.getByRole('button', {
            name: 'Run all scenarios',
        });
        this.confirmSaveScenarioButton = page
            .getByTestId('save-scenario-modal')
            .getByRole('button', { name: 'Save' });
        this.enterScenarioNameInput = page
            .getByTestId('save-scenario-modal')
            .locator('input#scenario-name')
            .first();
        this.confirmDeleteScenarioButton = page.getByRole('button', {
            name: 'danger Delete',
        });
        this.viewAllScenariosButton = page.getByRole('button', {
            name: '(View all)',
        });
        this.getScenarioRowByName = (scenarioName) => page.locator('tr', { hasText: scenarioName });
        this.getScenarioRow = (scenarioName) => page.locator('tr', { hasText: scenarioName });
        this.diagram = page.getByTestId('diagram');
        this.startInstanceButton = this.diagram.getByLabel('Start instance', {
            exact: true,
        });
        this.startInstanceWithCachedButton = page.getByLabel('Start instance with cached');
        this.notifications = page.locator('.cds--toast-notification');
        this.saveScenarioModal = page.getByTestId('save-scenario-modal');
        this.loadingInstanceDetailsText = this.page.getByText('Loading instance details...');
        this.retryButton = this.page.getByRole('button', { name: 'Retry' });
    }
    async waitForCompleteJobButtonToBeAvailable() {
        await (0, test_1.expect)(this.completeJobButton).toBeVisible({
            timeout: maxWaitTimeSeconds,
        });
    }
    async clickCompleteJobButton() {
        await this.completeJobButton.click();
    }
    async clickStartInstanceButton() {
        const maxRetries = 3;
        let attempts = 0;
        while (attempts < maxRetries) {
            try {
                await this.diagram.waitFor({ state: 'visible', timeout: 30000 });
                await this.startInstanceButton
                    .or(this.startInstanceWithCachedButton)
                    .first()
                    .click({ timeout: 30000 });
                await (0, test_1.expect)(this.loadingInstanceDetailsText).toBeVisible();
                await (0, test_1.expect)(this.loadingInstanceDetailsText).not.toBeVisible({
                    timeout: 60000,
                });
                return;
            }
            catch (error) {
                if (attempts >= maxRetries - 1)
                    throw error;
                await this.page.reload();
                await (0, sleep_1.sleep)(2000);
                attempts++;
            }
        }
    }
    async dismissStartModal() {
        const buttonVariations = [
            'Start a process instance',
            'Start another instance',
            'Start new instance',
            'Start instance',
        ];
        for (const buttonName of buttonVariations) {
            const button = this.page.getByRole('button', { name: buttonName });
            const count = await button.count();
            if (count > 0) {
                await button.click();
                return;
            }
        }
        throw new Error('Could not find start instance button with any expected variation');
    }
    async clickStartInstanceWithCachedButton() {
        await this.diagram.waitFor({ state: 'visible', timeout: 30000 });
        await this.startInstanceWithCachedButton.click({ timeout: 30000 });
    }
    async waitForInstanceDetailsToBeLoaded() {
        const maxRetries = 2;
        let attempts = 0;
        while (attempts < maxRetries) {
            try {
                await (0, test_1.expect)(this.page.getByText(/process instance key/i)).toBeVisible({
                    timeout: maxWaitTimeSeconds,
                });
                await (0, test_1.expect)(this.page.getByText(/This process instance has no variables/i)).toBeVisible({
                    timeout: maxWaitTimeSeconds,
                });
                return;
            }
            catch (error) {
                if (attempts >= maxRetries - 1)
                    throw error;
                await this.page.reload();
                attempts++;
            }
        }
    }
    async waitForNextElementToBeActive(historyItem) {
        const locator = this.page.getByText(new RegExp(`^${historyItem}`, 'i'));
        const maxRetries = 6; // ~1 min with the waits below
        for (let attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                await (0, test_1.expect)(locator.first()).toBeVisible({ timeout: 20000 });
                return;
            }
            catch (e) {
                if (attempt === maxRetries)
                    throw e;
                await this.page.reload();
                await this.diagram.waitFor({ state: 'visible', timeout: 30000 });
                await this.page.waitForTimeout(5000);
            }
        }
    }
    async waitForProcessToBeCompleted() {
        await (0, test_1.expect)(this.page.getByText('Completed')).toBeVisible({
            timeout: maxWaitTimeSeconds,
        });
    }
    async clickSaveScenarioButton() {
        await this.notifications
            .first()
            .waitFor({ state: 'hidden', timeout: 60000 })
            .catch(() => { });
        const isModalVisible = await this.saveScenarioModal
            .isVisible()
            .catch(() => false);
        if (!isModalVisible) {
            await (0, sleep_1.sleep)(3000);
            await (0, test_1.expect)(this.saveScenarioButton).toBeVisible({ timeout: 30000 });
            await (0, test_1.expect)(this.saveScenarioButton).toBeEnabled({ timeout: 30000 });
            await this.saveScenarioButton.click({ force: true, timeout: 30000 });
        }
    }
    async clickViewScenarioButton() {
        await this.viewScenarioButton.click();
    }
    async enterScenarioName(scenarioName) {
        await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, this.dialog, {
            postAction: async () => {
                await this.saveScenarioButton.click({ timeout: 30000 });
            },
        });
        const input = this.dialog.locator('input#scenario-name');
        await input.waitFor({ state: 'visible', timeout: 10000 });
        await input.clear();
        await input.fill(scenarioName);
    }
    async updateScenarioName(newScenarioName) {
        await this.enterScenarioNameInput.fill(newScenarioName);
    }
    async clickViewAllScenariosButton() {
        await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, this.viewAllScenariosButton);
        await this.viewAllScenariosButton.click();
    }
    async confirmSaveScenario() {
        await this.confirmSaveScenarioButton.click();
    }
    async getDeleteIconForScenario(scenarioName) {
        const scenarioRow = this.page
            .locator('tr')
            .filter({ has: this.page.getByText(scenarioName, { exact: true }) });
        return scenarioRow.getByLabel('Delete scenario');
    }
    async deleteScenario(scenarioName) {
        const deleteIcon = await this.getDeleteIconForScenario(scenarioName);
        await deleteIcon.click();
    }
    async confirmDeleteScenario() {
        await this.confirmDeleteScenarioButton.click();
    }
    async clickRunAllScenariosButton() {
        await this.runAllScenariosButton.click();
    }
    async clickmessagePublishButton() {
        await this.diagram.waitFor({ state: 'visible', timeout: 30000 });
        const publishIcon = this.diagram
            .locator('div.djs-overlays')
            .getByLabel('Publish message', { exact: true });
        await publishIcon.click({ timeout: 30000 });
    }
    async assertScenarioCompleted(scenarioName) {
        const scenarioRow = this.page.locator('tr', { hasText: scenarioName });
        const rowRetryButton = scenarioRow.getByRole('button', { name: 'Retry' });
        await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, scenarioRow.locator('text=Completed'), {
            totalTimeout: 90000,
            visibilityTimeout: 20000,
            postAction: async () => {
                if (await rowRetryButton.isVisible()) {
                    await rowRetryButton.click();
                }
            },
        });
    }
}
exports.PlayPage = PlayPage;
