"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleOrganizationPage = void 0;
const test_1 = require("@playwright/test");
const sleep_1 = require("../../utils/sleep");
const expectLocatorWithRetry_1 = require("../../utils/assertionHelpers/expectLocatorWithRetry");
class ConsoleOrganizationPage {
    page;
    usersTab;
    optionsButton;
    editUserMenuItem;
    modelerCheckbox;
    adminCheckbox;
    analystCheckbox;
    confirmButton;
    settingsTab;
    optInButton;
    optInCheckbox;
    newContextPadButton;
    newContextPadButtonText;
    mainUser;
    dialog;
    idComboBox;
    readPermissionCheckbox;
    startProcessIPermissionCheckbox;
    optInAICheckbox;
    rows;
    groupsTab;
    createGroupButton;
    createGroupSubButton;
    groupNameInput;
    noGroupsHeading;
    createFirstGroupButton;
    createGroupDialoge;
    assignMembersButton;
    assignMembersSubButton;
    assignMembersSearchbox;
    assignMembersSearchResult;
    organizationManagementLink;
    deleteSubButton;
    deleteButton;
    filterTableSearchbox;
    constructor(page) {
        this.page = page;
        this.usersTab = page.getByRole('tab', { name: 'Users' });
        this.optionsButton = page.getByRole('button', { name: 'Options' });
        this.editUserMenuItem = page.getByRole('menuitem', { name: 'Edit User' });
        this.modelerCheckbox = page
            .getByRole('group')
            .locator('label')
            .filter({ hasText: 'Modeler' });
        this.adminCheckbox = page
            .getByRole('group')
            .locator('label')
            .filter({ hasText: 'Admin' });
        this.analystCheckbox = page
            .getByRole('group')
            .locator('label')
            .filter({ hasText: 'Analyst' });
        this.confirmButton = page.getByRole('button', { name: 'Confirm' });
        this.settingsTab = page.getByRole('tab', { name: 'Settings' });
        this.optInButton = page.getByRole('button', { name: 'Opt-in', exact: true });
        this.optInCheckbox = page.getByLabel('I understand and agree to');
        this.newContextPadButton = page.getByRole('switch').last();
        this.newContextPadButtonText = page
            .locator('[class= "cds--toggle__text"]')
            .last();
        this.mainUser = page
            .getByRole('row')
            .filter({ hasText: process.env.C8_USERNAME });
        this.dialog = page.getByRole('dialog');
        this.idComboBox = page.getByRole('combobox', { name: 'ID' });
        this.readPermissionCheckbox = page.getByRole('checkbox', {
            name: 'Read definition',
        });
        this.startProcessIPermissionCheckbox = page.getByRole('checkbox', {
            name: 'Start process instance',
        });
        this.optInAICheckbox = page.getByLabel('I understand and agree to Terms for AI Usage');
        this.rows = this.page.getByRole('row');
        this.groupsTab = page.getByRole('tab', { name: 'Groups' });
        this.createGroupButton = page.getByRole('button', {
            name: 'create group',
        });
        this.createGroupSubButton = page
            .getByRole('button', {
            name: 'create group',
        })
            .last();
        this.groupNameInput = page.getByRole('textbox', { name: 'name' });
        this.noGroupsHeading = page.getByRole('heading', {
            name: 'you don’t have any groups yet',
        });
        this.createFirstGroupButton = page.getByRole('button', {
            name: 'create a group',
        });
        this.createGroupDialoge = page.getByRole('dialog', {
            name: 'create group',
        });
        this.assignMembersButton = page.getByRole('button', {
            name: 'assign members',
        });
        this.assignMembersSubButton = page
            .getByRole('button', {
            name: 'assign',
        })
            .last();
        this.assignMembersSearchbox = page.getByRole('searchbox', {
            name: 'search by full name or email address',
        });
        this.assignMembersSearchResult = page.locator('.cds--list-box__menu-item');
        this.organizationManagementLink = page.getByRole('link', {
            name: 'organization management',
        });
        this.deleteButton = page.getByRole('button', { name: 'delete' });
        this.deleteSubButton = page
            .getByRole('button', {
            name: 'danger',
        })
            .last();
        this.filterTableSearchbox = page.getByRole('searchbox', {
            name: 'Filter table',
        });
    }
    async filterTable(names) {
        for (const name of names) {
            await this.filterTableSearchbox.click({ timeout: 60000 });
            await this.filterTableSearchbox.fill(name);
        }
    }
    async clickProcessIdInput() {
        await (0, test_1.expect)(this.idComboBox).toBeVisible({ timeout: 60000 });
        await this.idComboBox.click();
    }
    async fillProcessIdInput(processId) {
        await this.idComboBox.fill(processId);
    }
    async checkReadPermissionCheckbox() {
        await (0, test_1.expect)(this.readPermissionCheckbox).toBeVisible({ timeout: 60000 });
        if (!(await this.readPermissionCheckbox.isChecked())) {
            await this.readPermissionCheckbox.click({ force: true });
        }
    }
    async checkStartInstancePermissionCheckbox() {
        if (!(await this.startProcessIPermissionCheckbox.isChecked({ timeout: 60000 }))) {
            await this.startProcessIPermissionCheckbox.click({ force: true });
        }
    }
    async clickUsersTab() {
        await this.usersTab.click({ timeout: 60000 });
    }
    async selectAnalystRole(username) {
        await this.filterTable([username]);
        await this.clickOptionsButton();
        await this.clickEditUserMenuItem();
        await this.checkAnalystCheckbox();
        await this.uncheckModelerCheckbox();
        await this.uncheckAdminCheckbox();
        await this.clickConfirmButton();
        await (0, test_1.expect)(this.page.getByText('Updating...')).not.toBeVisible({
            timeout: 90000,
        });
    }
    async selectModelerRole(username) {
        await this.filterTable([username]);
        await this.clickOptionsButton();
        await this.clickEditUserMenuItem();
        await this.uncheckAnalystCheckbox();
        await this.uncheckAdminCheckbox();
        await this.checkModelerCheckbox();
        await this.clickConfirmButton();
        await (0, test_1.expect)(this.page.getByText('Updating...')).not.toBeVisible({
            timeout: 90000,
        });
    }
    async selectAdminRole(username) {
        await this.filterTable([username]);
        await this.clickOptionsButton();
        await this.clickEditUserMenuItem();
        await this.uncheckAnalystCheckbox();
        await this.uncheckModelerCheckbox();
        await this.checkAdminCheckbox();
        await this.clickConfirmButton();
        await (0, test_1.expect)(this.page.getByText('Updating...')).not.toBeVisible({
            timeout: 90000,
        });
    }
    async clickOptionsButton() {
        await this.optionsButton.click({ timeout: 60000 });
    }
    async clickEditUserMenuItem() {
        await this.editUserMenuItem.click({ timeout: 60000 });
    }
    async checkModelerCheckbox() {
        if (!(await this.modelerCheckbox.isChecked({ timeout: 60000 }))) {
            await this.modelerCheckbox.click({ timeout: 60000 });
        }
    }
    async checkAdminCheckbox() {
        if (!(await this.adminCheckbox.isChecked({ timeout: 60000 }))) {
            await this.adminCheckbox.click({ timeout: 60000 });
        }
    }
    async checkAnalystCheckbox() {
        if (!(await this.analystCheckbox.isChecked({ timeout: 60000 }))) {
            await this.analystCheckbox.click({ timeout: 60000 });
        }
    }
    async uncheckAnalystCheckbox() {
        if (await this.analystCheckbox.isChecked({ timeout: 60000 })) {
            await this.analystCheckbox.click({ timeout: 60000 });
        }
    }
    async uncheckModelerCheckbox() {
        if (await this.modelerCheckbox.isChecked({ timeout: 60000 })) {
            await this.modelerCheckbox.click({ timeout: 60000 });
        }
    }
    async uncheckAdminCheckbox() {
        if (await this.adminCheckbox.isChecked({ timeout: 60000 })) {
            await this.adminCheckbox.click({ timeout: 60000 });
        }
    }
    async clickConfirmButton() {
        await this.confirmButton.click({ timeout: 60000 });
    }
    async clickSettingsTab() {
        await this.settingsTab.click({ timeout: 120000 });
        try {
            await (0, test_1.expect)(this.page.getByRole('heading', { name: 'Alpha features' })).toBeVisible({
                timeout: 120000,
            });
        }
        catch (error) {
            await this.settingsTab.click({ timeout: 120000 });
        }
    }
    async clickOptInButton() {
        await this.optInButton.click({ timeout: 60000 });
    }
    async enableAlphaFeature(name) {
        await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, this.rows.first(), {
            visibilityTimeout: 60000,
            totalTimeout: 300000,
            maxRetries: 5,
            postAction: async () => {
                await this.page.reload();
                await this.clickSettingsTab();
            },
        });
        const alphaFeature = this.rows.filter({ hasText: name }).first();
        if ((await alphaFeature.count()) < 1) {
            console.error(`No alpha feature(${name}) is found.`);
            return;
        }
        //Opt-in The Alpha Feature
        const alphaFeatureOptInButton = alphaFeature.getByRole('button', {
            name: 'Opt in to enable',
        });
        if (await alphaFeatureOptInButton.isVisible({ timeout: 10000 })) {
            if (await alphaFeatureOptInButton.isEnabled()) {
                await alphaFeatureOptInButton.click({ timeout: 90000 });
                await this.optInAICheckbox.scrollIntoViewIfNeeded();
                await this.optInAICheckbox.check({ timeout: 90000 });
                await (0, sleep_1.sleep)(3000);
            }
        }
        //Enable Alpha Feature
        const toggleText = await alphaFeature
            .locator('[class= "cds--toggle__text"]')
            .textContent();
        console.info(`Previous feature(${name}) setting is ${toggleText}.`);
        if (toggleText == 'Enabled') {
            console.log(`Feature ${name} is already enabled.`);
            return;
        }
        if (toggleText == 'Disabled') {
            await alphaFeature
                .locator('[class= "cds--toggle__switch"]')
                .first()
                .click();
            await (0, sleep_1.sleep)(10000);
        }
        await (0, test_1.expect)(alphaFeature.locator('[class= "cds--toggle__text"]')).toHaveText('Enabled');
    }
    async scrollToOptInCheckbox() {
        await this.page.locator('.ps-contract-scroll').evaluate((el) => {
            el.scrollTop = el.scrollHeight;
        });
    }
    async checkOptInCheckbox() {
        await this.optInCheckbox.check({ timeout: 90000 });
    }
    async clickMainUser() {
        await (0, test_1.expect)(this.mainUser).toBeVisible({ timeout: 60000 });
        await this.mainUser.click();
    }
    async clickNewContextPadButton() {
        try {
            await (0, test_1.expect)(this.newContextPadButtonText).toHaveText('Enabled', {
                timeout: 90000,
            });
        }
        catch {
            await this.page.reload();
            await this.newContextPadButton.click({ timeout: 90000 });
            await (0, test_1.expect)(this.newContextPadButtonText).toHaveText('Enabled', {
                timeout: 60000,
            });
        }
    }
    async optInToAlphaFeatures() {
        await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, this.rows.first(), {
            visibilityTimeout: 60000,
            totalTimeout: 140000,
            postAction: async () => {
                await this.page.reload();
            },
        });
        try {
            await (0, test_1.expect)(this.optInButton).toBeVisible({ timeout: 30000 });
            await this.clickOptInButton();
            await this.scrollToOptInCheckbox();
            await this.checkOptInCheckbox();
        }
        catch {
            await (0, test_1.expect)(this.optInButton).not.toBeVisible();
        }
    }
    async clickGroupsTab() {
        await this.groupsTab.click({ timeout: 60000 });
    }
    async clickCreateGroupButton() {
        const maxRetries = 3;
        for (let retries = 0; retries < maxRetries; retries++) {
            try {
                if (!(await this.noGroupsHeading.isVisible({ timeout: 120000 }))) {
                    await this.createGroupButton.click();
                }
                else {
                    await this.createFirstGroupButton.click();
                }
                return;
            }
            catch (error) {
                console.error(`Click attempt ${retries + 1} failed`);
            }
        }
        throw new Error(`Failed to click the button after ${maxRetries} attempts.`);
    }
    async fillGroupNameInput(name) {
        await this.groupNameInput.fill(name);
    }
    async clickCreateGroupSubButton() {
        await this.createGroupSubButton.click();
    }
    async clickUserGroup(name) {
        await this.page.getByRole('cell', { name: name }).click();
    }
    async clickAssignMembers() {
        await this.assignMembersButton.click();
    }
    async fillAssignMembers(names) {
        for (const name of names) {
            await this.assignMembersSearchbox.click();
            await this.assignMembersSearchbox.fill(name);
            await this.assignMembersSearchResult
                .filter({ hasText: name })
                .click({ timeout: 120000 });
        }
    }
    async clickAssignSubButton() {
        await this.assignMembersSubButton.click();
    }
    async clickOrganizationManagementLink() {
        await this.organizationManagementLink.click();
    }
    async deleteAllGroups() {
        try {
            await this.deleteButton
                .first()
                .waitFor({ state: 'visible', timeout: 60000 });
            const count = await this.deleteButton.count();
            if (count > 0) {
                for (let i = 0; i < count; i++) {
                    await this.deleteButton.nth(i).click({ timeout: 60000 });
                    await this.deleteSubButton.click({ timeout: 60000 });
                }
            }
        }
        catch (error) {
            console.log('Delete Button Not Clicked ' + error);
        }
    }
}
exports.ConsoleOrganizationPage = ConsoleOrganizationPage;
