"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelerCreatePage = void 0;
const test_1 = require("@playwright/test");
const sleep_1 = require("../../utils/sleep");
const randomSleep_1 = require("../../utils/randomSleep");
const ConnectorMarketplacePage_1 = require("../8.6/ConnectorMarketplacePage");
class ModelerCreatePage {
    page;
    generalPanel;
    idInput;
    startEventElement;
    appendTaskButton;
    appendGatewayButton;
    changeTypeButton;
    userTaskOption;
    parallelGatewayOption;
    appendEndEventButton;
    startInstanceMainButton;
    startInstanceSubButton;
    viewProcessInstanceLink;
    nameInput;
    diagramBreadcrumb;
    renameDiagramNameButton;
    diagramNameInput;
    variableInput;
    embedFormButton;
    embedButton;
    newForm;
    deployMainButton;
    deployMenuItem;
    additionalActionsButton;
    deploySubButton;
    cancelButton;
    restConnectorOption;
    webhookMessageStartEventConnectorOption;
    webhookTab;
    webhookIsActiveButton;
    copyWebhookUrlToClipboardButton;
    createTask;
    createEndEvent;
    canvas;
    endEventCanvas;
    connectToOtherElementButton;
    firstPlacedElement;
    secondPlacedElement;
    firstPlacedGateway;
    secondPlacedGateway;
    appendElementButton;
    marketPlaceButton;
    publicHolidayConnectorOption;
    publicHolidayYearOption;
    publicHolidayCountryCodeOption;
    implementationSection;
    implementationOptions;
    assignmentSection;
    priorityInput;
    firstElement;
    secondElement;
    thirdElement;
    payloadNameInput;
    payloadNumberInput;
    payloadCheckboxInput;
    payloadDateInput;
    form;
    formPropertySection;
    formLinkingTypeDropdown;
    formLinkTypeOptions;
    addFormJsonConfigurationInput;
    intermediateBoundaryEvent;
    intermediateWebhookConnectorOption;
    correlationKeyProcessInput;
    correlationKeyPayloadInput;
    closeButton;
    rbaEnabledDeployedDialog;
    viewProcessLink;
    assigneeInput;
    candidateGroupsInput;
    candidateUsersInput;
    serviceTaskOption;
    taskDefinitionPanel;
    jobTypeInput;
    playTab;
    continueToPlayButton;
    deployAndRunDialog;
    deployDiagramDialog;
    timerEventOption;
    timerEventSettings;
    timerType;
    timerValue;
    eighthPlacedElement;
    processIdSecondLocator;
    backupDeployButton;
    publicationSection;
    publicAccessToggle;
    publicationTab;
    copyPublicLinkButton;
    formLinkedSuccessMessage;
    diagramNameBreadcrumb;
    dialog;
    constructor(page) {
        this.page = page;
        this.generalPanel = page.locator('[data-group-id="group-general"]');
        this.idInput = page.getByLabel('ID', { exact: true });
        this.startEventElement = page.locator('.djs-hit').first();
        this.appendElementButton = page
            .locator('[class="djs-create-pad open djs-append-create-pad"]')
            .first();
        this.appendTaskButton = page.getByTitle('Append task');
        this.appendGatewayButton = page.getByTitle('append gateway');
        this.changeTypeButton = page.getByLabel('Change element');
        this.userTaskOption = page
            .getByRole('listitem', { name: 'User task' })
            .locator('span')
            .first();
        this.parallelGatewayOption = page.getByText('parallel gateway');
        this.appendEndEventButton = page.getByTitle('Append end event');
        this.deployAndRunDialog = page.getByRole('dialog', {
            name: 'Deploy & run diagram',
        });
        this.startInstanceMainButton = page.getByRole('button', {
            name: 'Deploy & run',
        });
        this.additionalActionsButton = page.getByRole('button', {
            name: 'Additional actions',
        });
        this.startInstanceSubButton = this.deployAndRunDialog
            .getByRole('button', { name: 'Deploy & run' })
            .last();
        this.viewProcessInstanceLink = page.getByRole('button', {
            name: 'View process instance',
        });
        this.viewProcessLink = page.getByRole('button', {
            name: 'View process in Operate',
        });
        this.nameInput = page.getByLabel('Name', { exact: true });
        this.diagramBreadcrumb = page.locator('[data-test="breadcrumb-diagram"]');
        this.renameDiagramNameButton = page.getByText('Rename');
        this.diagramNameInput = page.locator('[data-test="editable-input"]');
        this.variableInput = page.locator('textarea#variables-json');
        this.embedFormButton = page.getByRole('button', { name: 'Link form' });
        this.embedButton = page.locator('[data-test="confirm-move"]');
        this.newForm = page
            .locator('[data-test="item-New form"]')
            .getByText('New form');
        this.deployMainButton = page.locator('[data-test="deploy-button"]');
        this.deployMenuItem = page.getByRole('menuitem', {
            name: 'Deploy',
        });
        this.backupDeployButton = page.getByRole('button', {
            name: 'Deploy',
        });
        this.deploySubButton = page.locator('[data-test="deploy-action"]');
        this.cancelButton = page.getByRole('button', { name: 'Cancel' });
        this.restConnectorOption = page.getByRole('listitem', {
            name: 'REST Outbound Connector',
            exact: true,
        });
        this.webhookMessageStartEventConnectorOption = page.getByRole('listitem', {
            name: 'Webhook Message Start Event Connector',
            exact: true,
        });
        this.webhookTab = page.getByRole('tab', { name: 'Webhook' });
        this.webhookIsActiveButton = page.getByRole('button', {
            name: 'Webhook is active in Test',
        });
        this.copyWebhookUrlToClipboardButton = page.getByRole('textbox', {
            name: 'Copy to clipboard',
        });
        this.createTask = page.getByTitle('Create task');
        this.createEndEvent = page.getByTitle('Create end event');
        this.canvas = page.locator('rect').nth(1);
        this.endEventCanvas = page.locator('[class="bjs-container"]');
        this.connectToOtherElementButton = page
            .getByLabel('Connect to other element')
            .locator('path');
        this.firstPlacedElement = page.locator('g:nth-child(2) > .djs-element > .djs-hit');
        this.firstPlacedGateway = page
            .locator('[data-element-id*="Gateway"]')
            .first();
        this.secondPlacedElement = page
            .locator('[class= "djs-element djs-shape"]')
            .last();
        this.secondPlacedGateway = page
            .locator('[data-element-id*="Gateway"]')
            .last();
        this.marketPlaceButton = page.getByTitle('Browse Marketplace for more Connectors');
        this.publicHolidayConnectorOption = page
            .locator('[data-test="modeler"]')
            .getByText('Worldwide Public Holiday');
        this.publicHolidayYearOption = page.getByLabel('Year');
        this.publicHolidayCountryCodeOption = page.getByLabel('Countrycode');
        this.implementationSection = page.locator('[data-group-id="group-userTaskImplementation"]');
        this.implementationOptions = page.locator('#bio-properties-panel-userTaskImplementation');
        this.firstElement = page.locator('[class="djs-element djs-shape"]').nth(0);
        this.secondElement = page.locator('[class="djs-element djs-shape"]').nth(1);
        this.thirdElement = page.locator('[class="djs-element djs-shape"]').nth(2);
        this.assignmentSection = page.locator('[data-group-id="group-assignmentDefinition"]');
        this.form = page.locator('[class="fjs-container"]');
        this.priorityInput = page.getByRole('textbox', { name: 'priority' });
        this.payloadNameInput = page.getByLabel('Full Name');
        this.payloadDateInput = page.getByLabel('Date of Birth');
        this.payloadCheckboxInput = this.form.getByLabel('Agree');
        this.payloadNumberInput = this.form.getByLabel('Count');
        this.formPropertySection = page.locator('[data-group-id="group-form"]');
        this.formLinkingTypeDropdown = page.getByLabel('Type');
        this.formLinkTypeOptions = page.locator('#bio-properties-panel-formType');
        this.addFormJsonConfigurationInput = page.getByLabel('Form JSON configuration');
        this.intermediateBoundaryEvent = page.getByTitle('Append intermediate/boundary');
        this.intermediateWebhookConnectorOption = page.getByRole('listitem', {
            name: 'Webhook Intermediate Event',
        });
        this.correlationKeyPayloadInput = page.getByLabel('Correlation key (payload)');
        this.correlationKeyProcessInput = page.getByLabel('Correlation key (process)');
        this.serviceTaskOption = page.getByRole('listitem', { name: 'Service Task' });
        this.taskDefinitionPanel = page.locator('[data-group-id="group-taskDefinition"]');
        this.jobTypeInput = page.getByRole('textbox', { name: /job type/i });
        this.playTab = page.getByRole('tab', {
            name: 'Play',
        });
        this.closeButton = page.getByRole('button', { name: 'Close' });
        this.rbaEnabledDeployedDialog = page.getByRole('dialog', {
            name: 'Process successfully deployed',
        });
        this.assignmentSection = page.locator('[data-group-id="group-assignmentDefinition"]');
        this.assigneeInput = page.getByRole('textbox', { name: 'assignee' });
        this.candidateGroupsInput = page.getByRole('textbox', {
            name: 'candidate groups',
        });
        this.candidateUsersInput = page.getByRole('textbox', {
            name: 'candidate users',
        });
        this.appendGatewayButton = page.getByTitle('append gateway');
        this.parallelGatewayOption = page.getByText('parallel gateway');
        this.firstPlacedGateway = page
            .locator('[data-element-id*="Gateway"]')
            .first();
        this.secondPlacedGateway = page
            .locator('[data-element-id*="Gateway"]')
            .last();
        this.continueToPlayButton = page.getByRole('button', { name: 'Continue' });
        this.assigneeInput = page.getByRole('textbox', { name: 'assignee' });
        this.candidateGroupsInput = page.getByRole('textbox', {
            name: 'candidate groups',
        });
        this.deployDiagramDialog = page.getByRole('dialog', {
            name: 'Deploy diagram',
        });
        this.timerEventOption = page.getByRole('listitem', {
            name: 'Timer intermediate catch event',
            exact: true,
        });
        this.timerEventSettings = page.getByText(/^Timer$/).first();
        this.timerType = page.getByLabel('Type');
        this.timerValue = page.getByLabel('Value');
        this.eighthPlacedElement = page
            .locator('g:nth-child(8) > .djs-element > .djs-hit')
            .first();
        this.processIdSecondLocator = page.getByLabel('Process ID');
        this.publicationSection = page.locator('[data-group-id="group-process-publication"]');
        this.publicAccessToggle = page.getByRole('switch', {
            name: 'Toggle public access',
        });
        this.publicationTab = page.getByRole('tab', { name: 'Publication' });
        this.copyPublicLinkButton = page.getByRole('button', {
            name: 'Copy to clipboard',
        });
        this.formLinkedSuccessMessage = page
            .locator('.cds--toast-notification__subtitle')
            .getByText('Form has been successfully linked.');
        this.diagramNameBreadcrumb = (diagramName) => page.locator('button[data-test="breadcrumb-diagram"]', {
            hasText: diagramName,
        });
        this.dialog = page.getByRole('dialog');
    }
    async clickEditDiagramNameButton() {
        await this.renameDiagramNameButton.click({ timeout: 10000 });
    }
    async modelJobWorkerDiagram(processName, embedFrom = false) {
        await (0, test_1.expect)(this.generalPanel).toBeVisible({
            timeout: 120000,
        });
        await this.enterDiagramName(processName);
        await (0, sleep_1.sleep)(10000);
        await this.clickAppendElementButton();
        await this.clickAppendTaskButton();
        await this.clickChangeTypeButton();
        await this.clickUserTaskOption();
        await this.chooseImplementationOption('jobWorker');
        await (0, sleep_1.sleep)(3000);
        if (embedFrom) {
            await this.chooseFormLinkingTypeOption('Camunda Form (embedded)');
        }
        await this.clickAppendElementButton();
        await this.clickAppendEndEventButton();
        await (0, sleep_1.sleep)(20000);
    }
    async assertProcessInstanceLinkWithRetry(clusterName) {
        const maxRetries = 3;
        for (let attempt = 0; attempt < maxRetries; attempt++) {
            try {
                await (0, test_1.expect)(this.viewProcessInstanceLink).toBeVisible({
                    timeout: 30000,
                });
                return;
            }
            catch (error) {
                if (attempt < maxRetries - 1) {
                    console.warn(`View process instance status attempt ${attempt + 1} failed. Retrying...`);
                    await this.page.reload();
                    await (0, randomSleep_1.randomSleep)(10000, 30000);
                    await this.runProcessInstance(clusterName);
                }
                else {
                    throw new Error(`Assertion failed after ${maxRetries} attempts` + error);
                }
            }
        }
    }
    async modelCamundaUserTaskDiagram(processName, processId = '', formName = '') {
        await (0, test_1.expect)(this.generalPanel).toBeVisible({
            timeout: 180000,
        });
        await (0, sleep_1.sleep)(1000);
        await this.enterDiagramName(processName);
        await (0, sleep_1.sleep)(10000);
        if (processId.length > 0) {
            await this.clickStartEventElement();
            await this.clickGeneralPropertiesPanel();
            await this.clickIdInput();
            await this.fillIdInput(processId);
            await this.clickNameInput();
            await this.fillNameInput(processName);
            await this.clickStartEventElement();
        }
        await this.clickAppendElementButton();
        await this.clickAppendTaskButton();
        await this.clickChangeTypeButton();
        await this.clickUserTaskOption();
        await this.assertImplementationOption('zeebeUserTask');
        if (formName.length > 0) {
            await this.clickEmbedFormButton();
            await this.clickForm(formName);
            await this.clickEmbedButton();
        }
        await this.clickAppendElementButton();
        await this.clickAppendEndEventButton();
        await this.clickCanvas();
        await this.assertThreeElementsVisible();
        await (0, sleep_1.sleep)(20000);
    }
    async clickCandidateUsersInput() {
        await this.candidateUsersInput.click({ timeout: 60000 });
    }
    async clickSecondDeployButton() {
        await this.backupDeployButton.click({ timeout: 60000 });
    }
    async fillCandidateUsersInput(candidateUser) {
        await this.candidateUsersInput.fill(candidateUser, { timeout: 60000 });
    }
    async selectUserTask(userTask) {
        await this.page.locator(`g[data-element-id="${userTask}"]`).click();
    }
    async clickAssigneeInput() {
        await this.assigneeInput.click({ timeout: 60000 });
    }
    async fillAssigneeInput(name) {
        await this.assigneeInput.fill(name, { timeout: 60000 });
        await this.page.waitForTimeout(1000);
    }
    async clickUserTask(id) {
        const priorityUserTask = this.page.locator(`[data-element-id="${id}"]`);
        await priorityUserTask.click({ timeout: 60000 });
    }
    async clickForm(name) {
        await this.page
            .locator(`[data-test="item-${name}"]`)
            .getByText(name)
            .click({ timeout: 90000 });
    }
    async clickGeneralPropertiesPanel() {
        const isExpanded = (await this.generalPanel
            .locator('.bio-properties-panel-group-header.open')
            .count()) > 0;
        if (!isExpanded) {
            await this.generalPanel.click({ timeout: 60000 });
        }
    }
    async expandAssignmentSection() {
        const isExpanded = (await this.assignmentSection
            .locator('[data-group-id="group-assignmentDefinition"] .bio-properties-panel-group-header.open')
            .count()) > 0;
        if (!isExpanded) {
            await this.assignmentSection.click({ timeout: 60000 });
        }
    }
    async clickIdInput() {
        try {
            await this.idInput.click();
        }
        catch {
            await this.processIdSecondLocator.click();
        }
    }
    async fillIdInput(id) {
        try {
            await this.idInput.fill(id);
        }
        catch {
            await this.processIdSecondLocator.fill(id);
        }
    }
    async clickPriorityInput() {
        const isExpanded = (await this.assignmentSection
            .locator('.bio-properties-panel-group-header empty open')
            .count()) > 0;
        if (!isExpanded) {
            await this.assignmentSection.click();
        }
        await this.priorityInput.click({ timeout: 30000 });
    }
    async clickCloseButton() {
        await this.closeButton.click({ timeout: 60000 });
    }
    async clickAdditionalActionsButton() {
        await (0, test_1.expect)(this.additionalActionsButton).toBeVisible({ timeout: 20000 });
        await this.additionalActionsButton.click({ timeout: 60000 });
    }
    async clickDeployMenuItem() {
        await (0, test_1.expect)(this.deployMenuItem).toBeVisible({ timeout: 20000 });
        await this.deployMenuItem.click({ timeout: 60000 });
    }
    async deployDiagram(clusterName) {
        await this.clickDeployButtonWithRetry();
        await (0, test_1.expect)(this.deployDiagramDialog).toBeVisible({
            timeout: 30000,
        });
        //Select the correct cluster if multiple exist
        const cluster = this.deployDiagramDialog.getByText(clusterName);
        await (0, test_1.expect)(cluster).toBeVisible({
            timeout: 30000,
        });
        await cluster.click();
        await (0, test_1.expect)(this.deployDiagramDialog
            .locator('label')
            .filter({
            hasText: clusterName,
        })
            .getByRole('switch')).toBeChecked({ timeout: 30000 });
        //Check healthy status of the selected cluster
        const regex = new RegExp(`${clusterName}.*?HealthydevManage`);
        await (0, test_1.expect)(this.deployDiagramDialog).toHaveText(regex, {
            timeout: 120000,
        });
        await (0, test_1.expect)(this.deploySubButton).toBeVisible({
            timeout: 120000,
        });
        await this.clickDeploySubButtonWithRetry();
        await (0, test_1.expect)(this.viewProcessLink).toBeVisible({
            timeout: 180000,
        });
        await (0, test_1.expect)(this.viewProcessLink).toBeHidden({
            timeout: 120000,
        });
    }
    async runProcessInstance(clusterName, variables = '', formVariables = {}, textToVisible = '') {
        const maxRetries = 3;
        for (let attempt = 0; attempt < maxRetries; attempt++) {
            try {
                await (0, test_1.expect)(this.startInstanceMainButton).toBeVisible({
                    timeout: 60000,
                });
                await this.clickStartInstanceMainButton();
                await (0, test_1.expect)(this.deployAndRunDialog).toBeVisible({
                    timeout: 30000,
                });
                //Select the correct cluster if multiple exist
                const cluster = this.deployAndRunDialog.getByText(clusterName);
                await (0, test_1.expect)(cluster).toBeVisible({
                    timeout: 30000,
                });
                await cluster.click();
                await (0, test_1.expect)(this.deployAndRunDialog
                    .locator('label')
                    .filter({
                    hasText: clusterName,
                })
                    .getByRole('switch')).toBeChecked({ timeout: 30000 });
                //Check healthy status of the selected cluster
                const regex = new RegExp(`${clusterName}.*?HealthydevManage`);
                await (0, test_1.expect)(this.deployAndRunDialog).toHaveText(regex, {
                    timeout: 120000,
                });
                if (variables.length > 0) {
                    await (0, test_1.expect)(this.variableInput).toBeVisible({
                        timeout: 60000,
                    });
                    await this.clickVariableInput();
                    await this.fillVariableInput(variables);
                }
                if (Object.keys(formVariables).length > 0) {
                    if ('formName' in formVariables && formVariables['formName']) {
                        await this.fillStartFormName(formVariables['formName']);
                    }
                    if ('checkbox' in formVariables &&
                        formVariables['checkbox'] == 'true') {
                        await this.checkStartFormCheckbox();
                    }
                    if ('startDate' in formVariables && formVariables['startDate']) {
                        await this.fillStartFormDate(formVariables['startDate']);
                    }
                    if ('startNumber' in formVariables && formVariables['startNumber']) {
                        await this.fillStartFormNumber(formVariables['startNumber']);
                    }
                }
                if (textToVisible.length > 0) {
                    await (0, test_1.expect)(this.deployAndRunDialog.getByText(textToVisible)).toBeVisible({
                        timeout: 30000,
                    });
                }
                await this.clickStartInstanceSubButton();
                return;
            }
            catch (error) {
                if (attempt < maxRetries - 1) {
                    console.warn(`Attempt ${attempt + 1} failed for running process. Retrying...`);
                    await this.page.reload();
                    await (0, randomSleep_1.randomSleep)(10000, 30000);
                }
                else {
                    console.error(error);
                    throw new Error(`Assertion failed after ${maxRetries} attempts`);
                }
            }
        }
    }
    async fillPriorityInput(priority) {
        await this.priorityInput.fill(priority, { timeout: 60000 });
        await (0, test_1.expect)(this.page
            .getByText('Must be an expression, or an integer between 0 and 100')
            .first()).not.toBeVisible({ timeout: 30000 });
        await this.page.waitForTimeout(1000);
    }
    async clickStartEventElement() {
        await (0, test_1.expect)(this.startEventElement).toBeVisible({ timeout: 15000 });
        await this.startEventElement.click();
    }
    async clickAppendTaskButton() {
        await (0, test_1.expect)(this.appendTaskButton).toBeVisible({ timeout: 15000 });
        await this.appendTaskButton.click();
    }
    async clickAppendGatewayButton() {
        await (0, test_1.expect)(this.appendTaskButton).toBeVisible({ timeout: 15000 });
        await this.appendGatewayButton.click();
    }
    async clickChangeTypeButton() {
        await (0, test_1.expect)(this.changeTypeButton).toBeVisible({ timeout: 15000 });
        await this.changeTypeButton.click();
    }
    async clickUserTaskOption() {
        await (0, test_1.expect)(this.userTaskOption).toBeVisible({ timeout: 15000 });
        await this.userTaskOption.click();
    }
    async assertImplementationOption(implementationType) {
        await this.expandImplementationOptionIfNecessary();
        (0, test_1.expect)(await this.implementationOptions.inputValue()).toEqual(implementationType);
    }
    async expandImplementationOptionIfNecessary() {
        const isExpanded = (await this.implementationSection
            .locator('.bio-properties-panel-group-header empty open')
            .count()) > 0;
        if (!isExpanded) {
            await this.implementationSection.click();
        }
    }
    async clickParallelGatewayOption() {
        await this.parallelGatewayOption.click({ timeout: 90000 });
    }
    async clickAppendEndEventButton(parentElement) {
        try {
            await this.appendEndEventButton.click({ timeout: 120000 });
        }
        catch (error) {
            await this.page.reload();
            const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
            await sleep(10000);
            if (parentElement == undefined) {
                await this.clickSecondPlacedElement();
            }
            else if (parentElement == 'parallelGateway') {
                await this.clickSecondPlacedGateway();
            }
            await this.appendElementButton.hover();
            await this.appendEndEventButton.click({ timeout: 120000 });
        }
    }
    async addParallelUserTasks(numberOfTasks, taskName) {
        try {
            await this.clickAppendElementButton();
        }
        catch (error) {
            await this.page.reload();
            const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
            await sleep(10000);
            await this.clickFirstPlacedElement();
            await this.appendElementButton.hover();
        }
        await this.clickAppendGatewayButton();
        await this.clickChangeTypeButton();
        await this.clickParallelGatewayOption();
        await this.clickAppendElementButton();
        await this.clickAppendTaskButton();
        await this.clickChangeTypeButton();
        await this.clickUserTaskOption();
        await this.assertImplementationOption('zeebeUserTask');
        await this.clickGeneralPropertiesPanel();
        await this.clickNameInput();
        await this.fillNameInput(taskName + '1');
        await this.clickIdInput();
        await this.fillIdInput(taskName + '1');
        await this.clickAppendElementButton();
        await this.clickAppendGatewayButton();
        await this.clickChangeTypeButton();
        await this.clickParallelGatewayOption();
        for (let i = 2; i <= numberOfTasks; i++) {
            await this.clickFirstPlacedGateway();
            await this.clickAppendElementButton();
            await this.clickAppendTaskButton();
            await this.clickChangeTypeButton();
            await this.clickUserTaskOption();
            await this.assertImplementationOption('zeebeUserTask');
            await this.clickNameInput();
            await this.fillNameInput(taskName + i);
            await this.clickIdInput();
            await this.fillIdInput(taskName + i);
            await this.clickConnectToOtherElementButton();
            await this.clickSecondPlacedGateway();
            await this.clickCanvas();
        }
        await this.clickSecondPlacedGateway();
    }
    async clickStartInstanceMainButton() {
        await this.startInstanceMainButton.click({ timeout: 90000 });
    }
    async clickStartInstanceSubButton() {
        await this.startInstanceSubButton.click({ timeout: 90000 });
    }
    async clickViewProcessInstanceLink() {
        await this.viewProcessInstanceLink.click({ timeout: 180000 });
    }
    async clickNameInput() {
        await this.nameInput.click({ timeout: 60000 });
    }
    async fillNameInput(name) {
        await this.nameInput.fill(name, { timeout: 60000 });
    }
    async setPriority(taskName, priority, numberOfTasks) {
        for (let i = 1; i <= numberOfTasks; i++) {
            const userTaskId = taskName + i;
            const priorityUserTask = this.page.locator(`[data-element-id="${userTaskId}"]`);
            await priorityUserTask.click({ timeout: 60000 });
            await this.expandAssignmentSection();
            await this.clickPriorityInput();
            await this.fillPriorityInput(priority.toString());
            await (0, sleep_1.sleep)(5000);
            await this.clickCanvas();
            priority += 25;
        }
    }
    async clickDiagramBreadcrumb() {
        await this.diagramBreadcrumb.click({ timeout: 10000 });
    }
    async clickRenameDiagramNameButton() {
        await (0, test_1.expect)(this.renameDiagramNameButton).toBeVisible({ timeout: 30000 });
        await this.renameDiagramNameButton.click({ timeout: 30000 });
    }
    async assertThreeElementsVisible() {
        await (0, test_1.expect)(this.firstElement).toBeVisible({ timeout: 30000 });
        await (0, test_1.expect)(this.secondElement).toBeVisible({ timeout: 30000 });
        await (0, test_1.expect)(this.thirdElement).toBeVisible({ timeout: 30000 });
    }
    async enterDiagramName(name) {
        await this.diagramNameInput.fill(name, { timeout: 90000 });
        await this.diagramNameInput.press('Enter', { timeout: 90000 });
    }
    async clickVariableInput() {
        await this.variableInput.click({ timeout: 60000 });
    }
    async fillVariableInput(variable) {
        await this.variableInput.fill(variable);
    }
    async clickEmbedFormButton() {
        await this.embedFormButton.click({ timeout: 60000 });
    }
    async clickEmbedButton() {
        await this.embedButton.click({ timeout: 60000 });
    }
    async clickNewForm() {
        await this.newForm.click({ timeout: 120000 });
    }
    async clickDeployMainButton() {
        await this.deployMainButton.click({ timeout: 120000, force: true });
    }
    async clickDeploySubButton() {
        await this.deploySubButton.click({ timeout: 120000, force: true });
    }
    async clickCancelButton() {
        await this.cancelButton.click({ timeout: 60000 });
    }
    async clickRestConnectorOption() {
        await this.restConnectorOption.click({ timeout: 60000 });
    }
    async clickWebhookMessageStartEventConnectorOption() {
        await this.webhookMessageStartEventConnectorOption.click({ timeout: 60000 });
    }
    async clickWebhookTab() {
        await this.webhookTab.click({ timeout: 120000 });
    }
    async clickWebhookIsActiveButton() {
        await this.webhookIsActiveButton.click({ timeout: 60000 });
    }
    async clickDeployButton() {
        try {
            await this.clickAdditionalActionsButton();
            await this.clickDeployMenuItem();
            return;
        }
        catch (error) {
            await (0, test_1.expect)(this.deployMainButton).toBeVisible({
                timeout: 30000,
            });
            await this.deployMainButton.click({ timeout: 30000, force: true });
        }
    }
    async clickDeployButtonWithRetry(retries = 3) {
        for (let i = 0; i < retries; i++) {
            try {
                await this.clickDeployButton();
                return;
            }
            catch (error) {
                console.error(`Attempt ${i + 1} to click deploy button failed: ${error}`);
                // Refresh the page
                await this.page.reload();
                await (0, sleep_1.sleep)(10000);
            }
        }
        throw new Error(`Failed to click deploy button after ${retries} retries`);
    }
    async clickDeploySubButtonWithRetry(retries = 3) {
        for (let i = 0; i < retries; i++) {
            try {
                await this.deploySubButton.click({ timeout: 120000, force: true });
                return;
            }
            catch (error) {
                console.error(`Attempt ${i + 1} to click deploy button failed: ${error}`);
                await this.page.reload();
                await (0, sleep_1.sleep)(10000);
                await this.clickDeployButtonWithRetry();
            }
        }
        throw new Error(`Failed to click deploy button after ${retries} retries`);
    }
    async clickCreateTask() {
        await this.createTask.click({ timeout: 60000 });
    }
    async clickCreateEndEvent() {
        await this.createEndEvent.click({ timeout: 60000 });
    }
    async clickCanvas() {
        await this.canvas.click({ timeout: 60000 });
    }
    async clickEndEventCanvas() {
        await this.endEventCanvas.click({ timeout: 60000 });
    }
    async clickConnectToOtherElementButton() {
        await this.connectToOtherElementButton.click({ timeout: 60000 });
    }
    async clickFirstPlacedElement() {
        await this.firstPlacedElement.click({ timeout: 90000 });
    }
    async clickSecondPlacedElement() {
        await this.secondPlacedElement.click({ timeout: 12000 });
    }
    async clickSecondElement() {
        await this.secondElement.click({ timeout: 12000 });
    }
    async clickSecondPlacedGateway() {
        try {
            await this.secondPlacedGateway.click({ timeout: 60000 });
            await this.appendElementButton.isVisible({ timeout: 60000 });
        }
        catch (error) {
            await this.page.reload();
            const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
            await sleep(10000);
            await this.secondPlacedGateway.click({ timeout: 60000 });
        }
    }
    async clickFirstPlacedGateway() {
        try {
            await this.firstPlacedGateway.click({ timeout: 60000 });
            await this.appendElementButton.isVisible({ timeout: 60000 });
        }
        catch (error) {
            await this.page.reload();
            const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
            await sleep(10000);
            await this.firstPlacedGateway.click({ timeout: 60000 });
        }
    }
    async clickAppendElementButton() {
        for (let attempt = 1; attempt <= 4; attempt++) {
            try {
                await (0, sleep_1.sleep)(10000);
                await this.appendElementButton.hover({ timeout: 60000, force: true });
                return; // Exit loop if successful
            }
            catch (error) {
                if (attempt === 4)
                    throw error; // Rethrow after 3 failed attempts
            }
        }
    }
    async clickMarketPlaceButton() {
        const maxRetries = 3;
        for (let retries = 0; retries < maxRetries; retries++) {
            try {
                if (retries === 0) {
                    await this.marketPlaceButton.click({ timeout: 30000 });
                }
                else {
                    await this.changeTypeButton.click({ force: true, timeout: 30000 });
                    await this.marketPlaceButton.click({ timeout: 30000 });
                }
                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 clickPublicHolidayConnectorOption() {
        const maxRetries = 4;
        for (let retries = 0; retries < maxRetries; retries++) {
            try {
                if (retries <= 2) {
                    await this.publicHolidayConnectorOption.click({ timeout: 60000 });
                }
                else {
                    await this.clickMarketPlaceButton();
                    const connectorMarketplacePage = new ConnectorMarketplacePage_1.ConnectorMarketplacePage(this.page);
                    await connectorMarketplacePage.clickSearchForConnectorTextbox();
                    await connectorMarketplacePage.fillSearchForConnectorTextbox('Public Holiday Connector');
                    await (0, sleep_1.sleep)(10000);
                    await connectorMarketplacePage.downloadConnectorToProject();
                    await this.publicHolidayConnectorOption.click({ timeout: 120000 });
                }
                return;
            }
            catch (error) {
                console.error(`Click attempt ${retries + 1} failed: ${error}`);
                await this.page.reload();
                await new Promise((resolve) => setTimeout(resolve, 10000));
                await this.clickCanvas();
                await this.secondElement.click({ timeout: 60000 });
                await this.clickChangeTypeButton();
            }
        }
        throw new Error(`Failed to click the button after ${maxRetries} attempts.`);
    }
    async clickPublicHolidayYearOption() {
        await this.publicHolidayYearOption.click({ timeout: 60000 });
    }
    async fillPublicHolidayYearOption(year) {
        await this.publicHolidayYearOption.fill(year);
    }
    async clickPublicHolidayCountryCodeOption() {
        await this.publicHolidayCountryCodeOption.click({ timeout: 60000 });
    }
    async fillPublicHolidayCountryCodeOption(countryCode) {
        await this.publicHolidayCountryCodeOption.fill(countryCode);
    }
    async chooseImplementationOption(implementationType) {
        const isExpanded = (await this.implementationSection
            .locator('.bio-properties-panel-group-header.empty.open')
            .count()) > 0;
        if (!isExpanded) {
            await this.implementationSection.click();
        }
        await this.implementationOptions.selectOption(implementationType);
        await this.assertImplementationOption(implementationType);
    }
    async fillStartFormName(name) {
        await this.payloadNameInput.fill(name);
    }
    async fillStartFormDate(date) {
        await this.payloadDateInput.click();
        await this.payloadDateInput.fill(date);
        await this.payloadDateInput.press('Enter');
    }
    async checkStartFormCheckbox() {
        await this.payloadCheckboxInput.check();
    }
    async fillStartFormNumber(number) {
        await this.payloadNumberInput.fill(number);
    }
    async chooseFormLinkingTypeOption(formLinkType) {
        await this.formPropertySection.click();
        const jsonConfig = JSON.stringify({
            executionPlatform: 'Camunda Cloud',
            executionPlatformVersion: '8.6.0',
            exporter: {
                name: 'Camunda Web Modeler',
                version: 'ca7603f',
            },
            schemaVersion: 17,
            id: 'Form_0ex0ayi',
            components: [
                {
                    label: 'Full Name',
                    type: 'textfield',
                    id: 'Textfield_0',
                    validate: {
                        minLength: 2,
                        required: true,
                    },
                    key: 'fullName',
                },
            ],
            generated: true,
            type: 'default',
        });
        await this.formLinkTypeOptions.selectOption(formLinkType);
        await this.addFormJsonConfigurationInput.click();
        await this.addFormJsonConfigurationInput.fill(jsonConfig);
    }
    async clickIntermediateBoundaryEvent() {
        await this.intermediateBoundaryEvent.click({ timeout: 60000 });
    }
    async clickIntermediateWebhookConnectorOption() {
        await this.intermediateWebhookConnectorOption.click({ timeout: 60000 });
    }
    async clickCorrelationKeyProcessInput() {
        await this.correlationKeyProcessInput.click({ timeout: 60000 });
    }
    async fillCorrelationKeyProcessInput(correlationKeyProcess) {
        await this.correlationKeyProcessInput.fill(correlationKeyProcess);
    }
    async clickCorrelationKeyPayloadInput() {
        await this.correlationKeyPayloadInput.click({ timeout: 60000 });
    }
    async fillCorrelationKeyPayloadInput(correlationKeyPayload) {
        await this.correlationKeyPayloadInput.fill(correlationKeyPayload);
    }
    async clickServiceTaskOption() {
        const maxRetries = 3;
        for (let retries = 0; retries < maxRetries; retries++) {
            try {
                if (retries === 0) {
                    await this.serviceTaskOption.click({ timeout: 30000, force: true });
                }
                else {
                    await this.changeTypeButton.click({ force: true, timeout: 30000 });
                    await this.serviceTaskOption.click({ timeout: 30000, force: true });
                }
                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 clickTaskDefinitionPropertiesPanel() {
        const isExpanded = (await this.taskDefinitionPanel
            .locator('.bio-properties-panel-group-header empty open')
            .count()) > 0;
        if (!isExpanded) {
            await this.taskDefinitionPanel.click();
        }
    }
    async clickJobTypeInput() {
        await this.jobTypeInput.click();
    }
    async fillJobTypeInput(name) {
        await this.jobTypeInput.fill(name);
    }
    async switchToPlay() {
        await this.playTab.click();
    }
    async completePlayConfiguration(clusterName) {
        const timeout = 30000;
        let attempts = 0;
        const maxRetries = 2;
        while (attempts < maxRetries) {
            try {
                if (attempts > 0)
                    await this.switchToPlay(); // Call switchToPlay on subsequent attempts
                await this.selectCluster(clusterName);
                await this.continueToPlayButton.click({ timeout });
                await (0, test_1.expect)(this.page.getByText('Play environment is ready')).toBeVisible({ timeout: 90000 });
                return; // Exit if successful
            }
            catch (error) {
                if (attempts >= maxRetries - 1)
                    throw error;
                await this.page.reload();
                attempts++;
            }
        }
    }
    async selectCluster(clusterName) {
        await (0, test_1.expect)(this.dialog).toBeVisible({ timeout: 30000 });
        const healthCheckTimeout = 30000;
        const healthyRegex = new RegExp(`${clusterName}.*?HealthydevManage`);
        const cluster = this.dialog.getByText(clusterName);
        await (0, test_1.expect)(cluster).toBeVisible({ timeout: 30000 });
        await cluster.click();
        await (0, test_1.expect)(this.dialog
            .locator('label')
            .filter({ hasText: clusterName })
            .getByRole('switch')).toBeChecked({ timeout: 30000 });
        await (0, test_1.expect)(this.dialog).toHaveText(healthyRegex, {
            timeout: healthCheckTimeout,
        });
    }
    async clickCandidateGroupsInput() {
        await this.candidateGroupsInput.click({ timeout: 60000 });
    }
    async fillCandidateGroupsInput(name) {
        await this.candidateGroupsInput.fill(name, { timeout: 60000 });
        await this.page.waitForTimeout(1000);
    }
    async clickTimerEventOption() {
        await this.timerEventOption.click();
    }
    async clickTimerEventSettings() {
        await this.timerEventSettings.click();
    }
    async selectTimerType(type) {
        await this.timerType.selectOption(type);
    }
    async clickTimerValue() {
        await this.timerValue.click();
    }
    async fillTimerValue(value) {
        await this.timerValue.fill(value);
    }
    async clickEighthPlacedElement() {
        await this.eighthPlacedElement.click();
    }
    async expandFormsSection() {
        const isExpanded = (await this.formPropertySection
            .locator('[data-group-id="group-form"] .bio-properties-panel-group-header.open')
            .count()) > 0;
        if (!isExpanded) {
            await this.formPropertySection.click({ timeout: 60000 });
        }
    }
    async linkFormToStartEvent(formName) {
        await this.startEventElement.click({ timeout: 90000 });
        await (0, sleep_1.sleep)(1000);
        await this.embedForm(formName);
    }
    async expandPublicationSection() {
        const isExpanded = (await this.publicationSection
            .locator('.bio-properties-panel-group-header.open')
            .count()) > 0;
        if (!isExpanded) {
            await this.publicationSection.click({ timeout: 60000 });
        }
    }
    async enablePublicAccessIfDisabled() {
        await this.expandPublicationSection();
        const isDisabled = (await this.publicAccessToggle.getAttribute('aria-checked')) === 'false';
        if (isDisabled) {
            await this.publicAccessToggle.focus();
            await this.page.waitForTimeout(500);
            await this.publicAccessToggle.press('Space');
            await this.page.waitForTimeout(2000);
            await (0, test_1.expect)(this.page.getByText('Public access enabled')).toBeVisible({
                timeout: 60000,
            });
            console.log('Public access toggle enabled successfully');
        }
    }
    async clickPublicationTab() {
        await this.publicationTab.click({ timeout: 60000 });
    }
    async clickCopyPublicLinkButton() {
        await this.copyPublicLinkButton.click({ timeout: 60000 });
    }
    async getPublicationLink() {
        await this.clickPublicationTab();
        await (0, test_1.expect)(this.copyPublicLinkButton).toBeVisible({ timeout: 60000 });
        await this.clickCopyPublicLinkButton();
        await (0, sleep_1.sleep)(1000);
        const context = this.page.context();
        await context.grantPermissions(['clipboard-read']);
        const clipboardText = await this.page.evaluate(async () => {
            return await navigator.clipboard.readText();
        });
        console.log('Captured public link:', clipboardText);
        return clipboardText;
    }
    async embedForm(formName) {
        await this.clickEmbedFormButton();
        await this.clickForm(formName);
        await this.clickEmbedButton();
    }
    async assertFormEmbedded() {
        await (0, test_1.expect)(this.formLinkedSuccessMessage).toBeVisible({ timeout: 15000 });
    }
    async assertDiagramNameSet(diagramName) {
        await (0, test_1.expect)(this.diagramNameBreadcrumb(diagramName)).toBeVisible({
            timeout: 60000,
        });
    }
}
exports.ModelerCreatePage = ModelerCreatePage;
