"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 clickLocatorWithRetry_1 = require("../../utils/assertionHelpers/clickLocatorWithRetry");
const ClientCredentialsDetailsPage_1 = require("../8.7/ClientCredentialsDetailsPage");
const expectLocatorWithRetry_1 = require("../../utils/assertionHelpers/expectLocatorWithRetry");
class ClusterDetailsPage {
    page;
    apiTab;
    createFirstClientButton;
    clientNameTextbox;
    tasklistCheckbox;
    secretsCheckbox;
    optimizeCheckbox;
    operateCheckbox;
    createButton;
    closeModalButton;
    createClientButton;
    settingsTab;
    rbaEnableButton;
    rbaDisableButton;
    dialog;
    deleteButton;
    deleteSubButton;
    createClientCredentialsDialog;
    clientCredentialsDialog;
    clustersLink;
    userTaskRestriction;
    enableRBADialog;
    disableRBADialog;
    rbaEnabledMessage;
    alertsTab;
    alertsList;
    createFirstAlertButton;
    createNewAlertButton;
    emailRadioButton;
    createAlertsDialog;
    createAlertButton;
    createNewClientButton;
    clientsList;
    envVarsTab;
    zeebeCheckbox;
    apiClientNameTextbox;
    expandButton;
    rbaHeading;
    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')
            .filter({ hasText: 'Tasklist' });
        this.optimizeCheckbox = page
            .getByRole('dialog')
            .locator('label')
            .filter({ hasText: 'Optimize' });
        this.operateCheckbox = page
            .getByRole('dialog')
            .locator('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.clustersLink = page
            .getByRole('banner')
            .getByRole('link', { name: 'Clusters' });
        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.createNewClientButton = page.getByRole('button', {
            name: 'Create new client',
        });
        this.clientsList = page.getByRole('row').filter({ hasNotText: 'Scopes' });
        this.envVarsTab = this.clientCredentialsDialog.getByRole('tab', {
            name: 'Env Vars',
        });
        this.zeebeCheckbox = page
            .getByRole('dialog')
            .locator('label')
            .filter({ hasText: /^Zeebe$/ });
        this.apiClientNameTextbox = page.getByRole('textbox', {
            name: 'Client Name',
        });
        this.expandButton = page.locator('button[class="cds--table-expand__button"]');
        this.rbaHeading = this.page.getByRole('heading', {
            name: 'Resource-based authorizations',
        });
        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: 60000 });
        await this.apiTab.click({ timeout: 60000 });
    }
    async clickCreateClientButton() {
        await (0, clickLocatorWithRetry_1.clickLocatorWithRetry)(this.page, this.createFirstClientButton.or(this.createNewClientButton));
    }
    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 checkSecretsCheckbox() {
        if (!(await this.secretsCheckbox.isChecked())) {
            await this.secretsCheckbox.click();
        }
    }
    async clickOperateCheckbox() {
        await this.operateCheckbox.click({ timeout: 60000 });
    }
    async clickOptimizeCheckbox() {
        await this.optimizeCheckbox.click({ timeout: 60000 });
    }
    async clickCreateButton() {
        await this.createButton.click({ timeout: 60000 });
    }
    async clickCloseModalButton() {
        await this.closeModalButton.click({ timeout: 60000 });
    }
    async clickSettingsTab() {
        await this.settingsTab.click({ timeout: 60000 });
    }
    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();
                    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();
                    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 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 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();
    }
    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) {
        try {
            await (0, test_1.expect)(this.deleteButton.first()).toBeVisible({
                timeout: 10000,
            });
        }
        catch (error) {
            return; //No items found in the list
        }
        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 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: 120000,
                totalTimeout: 600000,
                maxRetries: 10,
                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 createAPIClientAndReturnVariables(name, setEnvVariables = true) {
        await this.createAPIClient(name);
        await this.clickEnvVarsButton();
        const variables = {
            zeebeAuthUrl: await this.clientCredentialsText(/export ZEEBE_AUTHORIZATION_SERVER_URL='([^']+)'/),
            zeebeClientId: await this.clientCredentialsText(/export ZEEBE_CLIENT_ID='([^']+)'/),
            zeebeClientSecret: await this.clientCredentialsText(/export ZEEBE_CLIENT_SECRET='([^']+)'/),
            zeebeUrl: await this.clientCredentialsText(/export ZEEBE_REST_ADDRESS='([^']+)'/),
            tokenAudience: await this.clientCredentialsText(/export ZEEBE_TOKEN_AUDIENCE='([^']+)'/),
        };
        if (setEnvVariables) {
            process.env.ZEEBE_API_CLIENT_ID = variables.zeebeClientId;
            process.env.ZEEBE_API_CLIENT_SECRET = variables.zeebeClientSecret;
            process.env.ZEEBE_API_AUTH_URL = variables.zeebeAuthUrl;
            process.env.ZEEBE_API_URL = variables.zeebeUrl;
            process.env.ZEEBE_API_TOKEN_AUDIENCE = variables.tokenAudience;
        }
        return variables;
    }
    async createAPIClient(name) {
        await this.clickCreateClientButton();
        await (0, test_1.expect)(this.createClientCredentialsDialog).toBeVisible();
        await this.fillAPIClientName(name);
        await this.checkZeebeCheckbox();
        await this.checkTasklistCheckbox();
        await this.checkOperateCheckbox();
        await this.checkOptimizeCheckbox();
        await this.checkSecretsCheckbox();
        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.')).toBeVisible();
        await (0, test_1.expect)(this.clientRow(name)).toContainText('Zeebe, Tasklist, Operate, Optimize, and Secrets');
    }
    async clickEnvVarsButton() {
        await (0, test_1.expect)(this.envVarsTab).toBeVisible({ timeout: 40000 });
        await this.envVarsTab.click();
    }
    async clientCredentialsText(regex) {
        const innerText = await this.clientCredentialsDialog.innerText();
        const match = innerText.match(regex);
        if (match && match[1]) {
            return match[1];
        }
        else {
            throw new Error(`No client credentials found by the regex expression ${regex}`);
        }
    }
    async checkTasklistCheckbox() {
        if (!(await this.tasklistCheckbox.isChecked())) {
            await this.tasklistCheckbox.click();
        }
    }
    async checkOptimizeCheckbox() {
        if (!(await this.optimizeCheckbox.isChecked())) {
            await this.optimizeCheckbox.click();
        }
    }
    async checkOperateCheckbox() {
        if (!(await this.operateCheckbox.isChecked())) {
            await this.operateCheckbox.click();
        }
    }
    async checkZeebeCheckbox() {
        if (!(await this.zeebeCheckbox.isChecked())) {
            await this.zeebeCheckbox.click();
        }
    }
    async fillAPIClientName(name) {
        await this.apiClientNameTextbox.fill(name);
    }
    async clickExpandButton() {
        await this.expandButton.click({ timeout: 60000 });
    }
    async clickReviewUpdateButton() {
        await this.reviewUpdateButton.click({ timeout: 60000 });
    }
    async performClusterUpdate() {
        await this.clickReviewUpdateButton();
        await (0, test_1.expect)(this.updateAvailableDialog).toBeVisible({ timeout: 30000 });
        await this.updateButton.click({ timeout: 60000 });
    }
}
exports.ClusterDetailsPage = ClusterDetailsPage;
