"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClusterDetailsPage = void 0;
const test_1 = require("@playwright/test");
const sleep_1 = require("../../utils/sleep");
const ClientCredentialsDetailsPage_1 = require("../8.6/ClientCredentialsDetailsPage");
const clickLocatorWithRetry_1 = require("../../utils/assertionHelpers/clickLocatorWithRetry");
const expectLocatorWithRetry_1 = require("../../utils/assertionHelpers/expectLocatorWithRetry");
class ClusterDetailsPage {
    page;
    apiTab;
    createFirstClientButton;
    clientNameTextbox;
    tasklistCheckbox;
    optimizeCheckbox;
    secretsCheckbox;
    operateCheckbox;
    createButton;
    closeModalButton;
    clientsList;
    createClientButton;
    settingsTab;
    rbaEnableButton;
    rbaDisableButton;
    dialog;
    enableRBADialog;
    disableRBADialog;
    deleteButton;
    deleteSubButton;
    createClientCredentialsDialog;
    clientCredentialsDialog;
    userTaskRestriction;
    alertsTab;
    alertsList;
    createFirstAlertButton;
    createNewAlertButton;
    emailRadioButton;
    createAlertsDialog;
    createAlertButton;
    rbaHeading;
    rbaEnabledMessage;
    clientCredentialsLink;
    clientRow;
    clientRowDeleteButton;
    reviewUpdateButton;
    updateAvailableDialog;
    updateButton;
    constructor(page) {
        this.page = page;
        this.apiTab = page.getByRole('tab', { name: 'API' });
        this.createFirstClientButton = page.getByRole('button', {
            name: 'Create your first Client',
        });
        this.clientNameTextbox = page.getByRole('textbox', { name: 'Client Name' });
        this.tasklistCheckbox = page
            .getByRole('dialog')
            .locator('label.cds--checkbox-label')
            .filter({ hasText: /^Tasklist$/ });
        this.optimizeCheckbox = page
            .getByRole('dialog')
            .locator('label.cds--checkbox-label')
            .filter({ hasText: /^Optimize$/ });
        this.operateCheckbox = page
            .getByRole('dialog')
            .locator('label.cds--checkbox-label')
            .filter({ hasText: /^Operate$/ });
        this.secretsCheckbox = page
            .getByRole('dialog')
            .locator('label')
            .filter({ hasText: /^Secrets$/ });
        this.createButton = page.getByRole('button', { name: 'Create', exact: true });
        this.closeModalButton = page
            .getByRole('dialog', { name: 'Client credentials', exact: true })
            .getByLabel('Close');
        this.createClientButton = page.getByRole('button', {
            name: 'Create new Client',
        });
        this.settingsTab = page.getByRole('tab', { name: 'Settings' });
        this.dialog = page.getByRole('dialog');
        this.enableRBADialog = page.getByRole('dialog', {
            name: 'Enable resource-based authorizations',
            exact: true,
        });
        this.disableRBADialog = page.getByRole('dialog', {
            name: 'Disable resource-based authorizations',
            exact: true,
        });
        this.rbaEnableButton = this.enableRBADialog.getByRole('button', {
            name: 'Enable',
        });
        this.rbaDisableButton = this.disableRBADialog.getByRole('button', {
            name: 'Disable',
        });
        this.deleteButton = page.getByRole('button', { name: 'Delete' });
        this.deleteSubButton = page.getByRole('button', {
            name: 'danger Delete',
        });
        this.createClientCredentialsDialog = page.getByRole('dialog', {
            name: 'Create new client credentials',
        });
        this.clientCredentialsDialog = page.getByRole('dialog', {
            name: 'Client credentials',
            exact: true,
        });
        this.userTaskRestriction = page.locator('button[aria-label="Switch Enforce user task restrictions"]');
        this.rbaEnabledMessage = page.getByText('Resource-based authorizations enabled');
        this.alertsTab = page.getByRole('tab', { name: 'Alerts' });
        this.alertsList = page
            .getByRole('row')
            .filter({ hasNotText: 'Delivery method' }); //Filter out header row
        this.createFirstAlertButton = page.getByRole('button', {
            name: 'Create an alert',
        });
        this.createNewAlertButton = page.getByRole('button', {
            name: 'Create new alert',
        });
        this.emailRadioButton = page.getByRole('radio', {
            name: 'Email',
        });
        this.createAlertsDialog = page.getByRole('dialog', {
            name: 'Create process incident alert',
        });
        this.createAlertButton = page.getByRole('button', {
            name: 'Create alert',
            exact: true,
        });
        this.rbaHeading = this.page.getByRole('heading', {
            name: 'Resource-based authorizations',
        });
        this.clientsList = page.getByRole('row').filter({ hasNotText: 'Scopes' });
        this.clientCredentialsLink = (clientCredentials) => page
            .getByRole('cell', { name: clientCredentials })
            .getByText(clientCredentials);
        this.clientRow = (name) => this.clientsList.filter({ hasText: name });
        this.clientRowDeleteButton = (name) => this.clientRow(name).getByRole('button', { name: 'Delete' });
        this.reviewUpdateButton = page.getByRole('button', { name: 'Review Update' });
        this.updateAvailableDialog = page
            .locator('.cds--modal-container')
            .filter({ hasText: 'Update available' });
        this.updateButton = this.updateAvailableDialog.getByRole('button', {
            name: 'Update',
        });
    }
    async clickAPITab() {
        await (0, test_1.expect)(this.apiTab).toBeVisible({ timeout: 15000 });
        await this.apiTab.click({ timeout: 15000 });
    }
    async deleteAPIClientsIfExist(name) {
        if (name) {
            const row = this.clientRow(name);
            const deleteButton = this.clientRowDeleteButton(name);
            try {
                await (0, test_1.expect)(deleteButton).toBeVisible({ timeout: 10000 });
                await deleteButton.click();
                await (0, test_1.expect)(this.dialog).toBeVisible();
                await this.deleteSubButton.click();
                await (0, test_1.expect)(this.page.getByText('Deleting...')).not.toBeVisible({
                    timeout: 10000,
                });
                await (0, test_1.expect)(row).not.toBeVisible();
            }
            catch (error) {
                console.warn(`No client row found for ${name} or deletion failed: ${error}`);
            }
            return;
        }
        await this.doDelete(this.dialog, 'API clients');
    }
    async clickAlertsTab() {
        await (0, test_1.expect)(this.alertsTab).toBeVisible({ timeout: 40000 });
        await this.alertsTab.click();
        // Wait for page to load - either button will be visible depending on whether alerts exist
        await (0, test_1.expect)(async () => {
            const hasCreateFirst = await this.createFirstAlertButton.isVisible();
            const hasCreateNew = await this.createNewAlertButton.isVisible();
            (0, test_1.expect)(hasCreateFirst || hasCreateNew).toBe(true);
        }).toPass({ timeout: 30000, intervals: [2000] });
    }
    async clickCreateFirstAlertButton() {
        await (0, test_1.expect)(this.createFirstAlertButton).toBeVisible({ timeout: 40000 });
        await this.createFirstAlertButton.click();
    }
    async clickCreateNewAlertButton() {
        await (0, test_1.expect)(this.createNewAlertButton).toBeVisible({ timeout: 60000 });
        await this.createNewAlertButton.click();
        await (0, test_1.expect)(this.page.getByText('Creating...')).not.toBeVisible({
            timeout: 60000,
        });
    }
    async createAlert(isFirstAlert = true) {
        if (isFirstAlert) {
            await this.clickCreateFirstAlertButton();
        }
        else {
            await this.clickCreateNewAlertButton();
        }
        await (0, test_1.expect)(this.createAlertsDialog).toBeVisible();
        await this.selectEmailRadioButton();
        await this.clickCreateAlertButton();
    }
    async selectEmailRadioButton() {
        await (0, test_1.expect)(this.emailRadioButton).toBeVisible({ timeout: 60000 });
        await this.emailRadioButton.click({ force: true });
    }
    async clickCreateAlertButton() {
        await (0, test_1.expect)(this.createAlertButton).toBeVisible({ timeout: 60000 });
        await this.createAlertButton.click();
        await (0, test_1.expect)(this.page.getByText('Creating...')).not.toBeVisible({
            timeout: 60000,
        });
    }
    async deleteAlerts() {
        await this.doDelete(this.dialog, 'Alerts');
    }
    async doDelete(dialog, text) {
        if ((await this.deleteButton.count()) <= 0) {
            console.log(`No delete button found, skipping deletion.`);
            return;
        }
        try {
            let deletes = await this.deleteButton.all();
            while (deletes.length > 0) {
                const deleteButton = deletes[0];
                if (await deleteButton.isVisible()) {
                    await deleteButton.click({ timeout: 60000 });
                    await (0, test_1.expect)(dialog).toBeVisible({ timeout: 40000 });
                    await this.deleteSubButton.click();
                    await (0, test_1.expect)(this.page.getByText('Deleting...')).not.toBeVisible({
                        timeout: 60000,
                    });
                }
                await (0, sleep_1.sleep)(3000);
                deletes = await this.deleteButton.all();
            }
            await (0, test_1.expect)(this.deleteButton).not.toBeVisible({
                timeout: 30000,
            });
        }
        catch (error) {
            console.error(`Error during ${text} deletion: `, error);
        }
    }
    async clickCreateClientButton() {
        await (0, clickLocatorWithRetry_1.clickLocatorWithRetry)(this.page, this.createFirstClientButton.or(this.createClientButton));
    }
    async clickCreateFirstClientButton() {
        const maxRetries = 3;
        for (let retries = 0; retries < maxRetries; retries++) {
            try {
                if (retries === 0) {
                    await this.createFirstClientButton.click({ timeout: 60000 });
                }
                else {
                    await this.page
                        .getByRole('banner')
                        .getByRole('link', { name: 'Clusters' })
                        .click({ timeout: 60000 });
                    await await this.createFirstClientButton.click({ timeout: 60000 });
                }
                return;
            }
            catch (error) {
                console.error(`Click attempt ${retries + 1} failed: ${error}`);
                await new Promise((resolve) => setTimeout(resolve, 10000));
            }
        }
        throw new Error(`Failed to click the button after ${maxRetries} attempts.`);
    }
    async reload() {
        await this.page.reload();
    }
    async clickClientNameTextbox() {
        await this.clientNameTextbox.click({ timeout: 60000 });
    }
    async fillClientNameTextbox(name) {
        await this.clientNameTextbox.fill(name, { timeout: 60000 });
    }
    async clickTasklistCheckbox() {
        await this.tasklistCheckbox.click({ timeout: 60000 });
    }
    async clickOperateCheckbox() {
        await this.operateCheckbox.click({ timeout: 60000 });
    }
    async clickOptimizeCheckbox() {
        await this.optimizeCheckbox.click({ timeout: 60000 });
    }
    async clickSecretsCheckbox() {
        if (!(await this.secretsCheckbox.isChecked())) {
            await this.secretsCheckbox.click();
        }
    }
    async clickCreateButton() {
        await this.createButton.click({ timeout: 60000 });
    }
    async clickCloseModalButton() {
        await this.closeModalButton.click({ timeout: 60000 });
    }
    async clickSettingsTab() {
        await this.settingsTab.click({ timeout: 120000 });
        try {
            await (0, test_1.expect)(this.page.getByRole('heading', { name: 'cluster settings' })).toBeVisible({
                timeout: 120000,
            });
        }
        catch (error) {
            await this.settingsTab.click({ timeout: 120000 });
        }
    }
    async createAPIClient(name) {
        await this.clickCreateClientButton();
        await (0, test_1.expect)(this.createClientCredentialsDialog).toBeVisible({
            timeout: 60000,
        });
        await this.clickClientNameTextbox();
        await this.fillClientNameTextbox(name);
        await this.clickTasklistCheckbox();
        await this.clickOperateCheckbox();
        await this.clickOptimizeCheckbox();
        await this.clickSecretsCheckbox();
        await this.clickCreateButton();
        await (0, test_1.expect)(this.clientCredentialsDialog).toBeVisible({
            timeout: 20000,
        });
        await (0, test_1.expect)(this.clientCredentialsDialog
            .getByText('The Client Secret will not be shown again.')
            .first()).toBeVisible({
            timeout: 60000,
        });
    }
    async searchAndClickClientCredentialsLink(name) {
        await (0, test_1.expect)(this.clientsList.first()).toBeVisible({ timeout: 60000 });
        const clientLink = this.clientCredentialsLink(name);
        await (0, test_1.expect)(clientLink).toBeVisible({ timeout: 30000 });
        await clientLink.click();
        const clientCredentialsDetailsPage = new ClientCredentialsDetailsPage_1.ClientCredentialsDetailsPage(this.page);
        await clientCredentialsDetailsPage.isOpen(name);
        return clientCredentialsDetailsPage;
    }
    async enableRBA() {
        await (0, test_1.expect)(this.rbaHeading).toBeVisible({ timeout: 60000 });
        // Locate all elements with class .cds--toggle__text
        const toggleTextElements = await this.page.$$('.cds--toggle__text');
        // Check if toggleTextElements has at least 2 elements
        if (toggleTextElements.length >= 2) {
            // Get the text content of the second toggle text element
            const toggleText = await toggleTextElements[1].textContent();
            // Check if the text content is 'Disabled'
            if (toggleText === 'Disabled') {
                // Locate all elements with class .cds--toggle__switch
                const toggleSwitchElements = await this.page.$$('.cds--toggle__switch');
                // Check if toggleSwitchElements has at least 2 elements
                if (toggleSwitchElements.length >= 2) {
                    // Click the second toggle switch element
                    await toggleSwitchElements[1].click();
                    console.log('Second toggle switch clicked.');
                    await (0, test_1.expect)(this.enableRBADialog).toBeVisible({ timeout: 60000 });
                    await this.rbaEnableButton.click({ timeout: 60000 });
                    await (0, test_1.expect)(this.page.getByText('Enabling...')).not.toBeVisible({
                        timeout: 60000,
                    });
                }
                else {
                    console.log('Second toggle switch not found or less than 2.');
                }
            }
            else {
                console.log("Second toggle text does not contain 'Disabled'.");
            }
        }
        else {
            console.log('Toggle text elements not found or less than 2.');
        }
    }
    async disableRBA() {
        await (0, test_1.expect)(this.rbaHeading).toBeVisible({ timeout: 60000 });
        // Locate all elements with class .cds--toggle__text
        const toggleTextElements = await this.page.$$('.cds--toggle__text');
        // Check if toggleTextElements has at least 2 elements
        if (toggleTextElements.length >= 2) {
            // Get the text content of the second toggle text element
            const toggleText = await toggleTextElements[1].textContent();
            // Check if the text content is 'Enabled'
            if (toggleText === 'Enabled') {
                // Locate all elements with class .cds--toggle__switch
                const toggleSwitchElements = await this.page.$$('.cds--toggle__switch');
                // Check if toggleSwitchElements has at least 2 elements
                if (toggleSwitchElements.length >= 2) {
                    // Click the second toggle switch element
                    await toggleSwitchElements[1].click();
                    console.log('Second toggle switch clicked.');
                    await (0, test_1.expect)(this.disableRBADialog).toBeVisible({ timeout: 60000 });
                    await this.rbaDisableButton.click({ timeout: 60000 });
                    await (0, test_1.expect)(this.page.getByText('Disabling...')).not.toBeVisible({
                        timeout: 60000,
                    });
                }
                else {
                    console.log('Second toggle switch not found or less than 2.');
                }
            }
            else {
                console.log("Second toggle text does not contain 'Enabled'.");
            }
        }
        else {
            console.log('Toggle text elements not found or less than 2.');
        }
    }
    async assertComponentsHealth(components = ['Zeebe', 'Tasklist', 'Operate', 'Optimize']) {
        for (const component of components) {
            await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, this.page.getByText(`${component}Healthy`, { exact: true }), {
                visibilityTimeout: 60000,
                totalTimeout: 400000,
                maxRetries: 7,
                preAction: async () => {
                    await this.page.reload();
                },
            });
        }
    }
    async userTaskEnabledAssertion() {
        try {
            await (0, test_1.expect)(await this.userTaskRestriction.getAttribute('aria-checked')).toBe('true');
        }
        catch (error) {
            await this.page.reload();
            await (0, test_1.expect)(this.userTaskRestriction.getAttribute('aria-checked')).toBe('true');
        }
    }
    async clickReviewUpdateButton() {
        await this.reviewUpdateButton.click({ timeout: 60000 });
    }
    async clickUpdateButton() {
        await this.updateButton.click({ timeout: 60000 });
    }
    async performClusterUpdate() {
        await this.clickReviewUpdateButton();
        await this.page.waitForTimeout(1000);
        await (0, test_1.expect)(this.updateAvailableDialog).toBeVisible({ timeout: 60000 });
        await this.clickUpdateButton();
    }
}
exports.ClusterDetailsPage = ClusterDetailsPage;
