"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 clickLocatorWithRetry_1 = require("../../utils/assertionHelpers/clickLocatorWithRetry");
const env_1 = require("../../utils/env");
const maxWaitTimeSeconds = 180000;
// OpenSearch indexes process instances more slowly than Elasticsearch, so
// "Loading instance details..." can stay visible longer than the default 60s.
const loadingDetailsHideTimeout = env_1.isOpenSearch ? 180000 : 60000;
class PlayPage {
    page;
    completeJobButton;
    saveScenarioButton;
    viewScenarioButton;
    runAllScenariosButton;
    confirmSaveScenarioButton;
    enterScenarioNameInput;
    confirmDeleteScenarioButton;
    viewAllScenariosButton;
    getScenarioRowByName;
    getScenarioRow;
    diagram;
    startInstanceButton;
    notifications;
    saveScenarioModal;
    dialog;
    loadingInstanceDetailsText;
    retryButton;
    restartProcess;
    completedMessage;
    constructor(page) {
        this.page = page;
        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.dialog = page.getByRole('dialog');
        this.confirmSaveScenarioButton = page.getByRole('button', {
            name: 'Save',
            exact: true,
        });
        this.enterScenarioNameInput = page
            .getByTestId('save-scenario-modal')
            .first()
            .locator('input#scenario-name')
            .first();
        this.confirmDeleteScenarioButton = page.getByRole('button', {
            name: 'danger Delete',
        });
        this.viewAllScenariosButton = page.getByText('(View all)').last();
        this.getScenarioRowByName = (scenarioName) => page.locator('tr', { hasText: scenarioName });
        this.getScenarioRow = (scenarioName) => page.locator('tr', { hasText: scenarioName });
        this.diagram = page.getByTestId('diagram');
        this.startInstanceButton = page.getByTestId('undefined-Start instance');
        this.notifications = page.locator('.cds--toast-notification');
        this.saveScenarioModal = page.getByTestId('save-scenario-modal').first();
        this.loadingInstanceDetailsText = this.page.getByText('Loading instance details...');
        this.retryButton = this.page.getByRole('button', { name: 'Retry' });
        this.restartProcess = this.page.getByRole('button', {
            name: 'Restart process',
        });
        this.completedMessage = this.page.getByText(/completed manually/i);
    }
    async waitForCompleteJobButtonToBeAvailable() {
        await (0, test_1.expect)(this.completeJobButton).toBeVisible({
            timeout: maxWaitTimeSeconds,
        });
    }
    async clickCompleteJobButton() {
        await (0, test_1.expect)(this.completeJobButton).toBeVisible({ timeout: 30000 });
        await (0, test_1.expect)(this.completeJobButton).toBeEnabled({ timeout: 30000 });
        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.click({ timeout: 30000 });
                await (0, test_1.expect)(this.loadingInstanceDetailsText).toBeVisible();
                await (0, test_1.expect)(this.loadingInstanceDetailsText).not.toBeVisible({
                    timeout: loadingDetailsHideTimeout,
                });
                await (0, test_1.expect)(this.dialog).not.toBeVisible({ timeout: 15000 });
                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('dialog')
                .getByRole('button', { name: buttonName });
            const count = await button.count();
            if (count > 0) {
                await button.click();
                return;
            }
        }
        // No modal present — Play loaded directly without a start modal (env already provisioned)
    }
    async waitForInstanceDetailsToBeLoaded() {
        const maxRetries = 3;
        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();
                const startButton = this.restartProcess.or(this.startInstanceButton);
                await startButton.waitFor({ state: 'visible', timeout: 30000 });
                await startButton.click();
                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;
                // force UI to update
                await this.page.reload();
                await this.diagram.waitFor({ state: 'visible', timeout: 30000 });
                await this.page.waitForTimeout(5000);
            }
        }
    }
    async waitForProcessToBeCompleted() {
        const incidentText = await this.page.getByText(/incident/i).count();
        if (incidentText > 0) {
            throw new Error('Process has an incident instead of completing');
        }
        await (0, test_1.expect)(this.completedMessage.first()).toBeVisible({
            timeout: maxWaitTimeSeconds,
        });
        await (0, test_1.expect)(this.completedMessage.first()).not.toBeVisible({
            timeout: 60000,
        });
    }
    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() {
        // The "(View all)" button is rendered after a save-scenario toast settles.
        // Reload + retry to recover when the toast or notification panel covers it.
        await (0, clickLocatorWithRetry_1.clickLocatorWithRetry)(this.page, this.viewAllScenariosButton, {
            totalTimeout: 180000,
            visibilityTimeout: 30000,
            maxRetries: 8,
            preAction: async () => {
                await this.notifications
                    .first()
                    .waitFor({ state: 'hidden', timeout: 10000 })
                    .catch(() => { });
            },
            postAction: async () => {
                // Recovery: reload the page so the Play UI re-fetches scenario state
                // and renders the "(View all)" button when multiple scenarios exist.
                await this.page.reload();
                await this.diagram
                    .waitFor({ state: 'visible', timeout: 30000 })
                    .catch(() => { });
            },
        });
    }
    async confirmSaveScenario() {
        await this.confirmSaveScenarioButton.click({ timeout: 30000 });
    }
    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) {
        await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, this.page
            .locator('tr', { hasText: scenarioName })
            .locator('text=Completed'), {
            totalTimeout: 90000,
            visibilityTimeout: 20000,
            postAction: async () => {
                if (await this.retryButton.first().isVisible()) {
                    await this.retryButton.first().click();
                }
            },
        });
    }
}
exports.PlayPage = PlayPage;
