"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 clickLocatorWithRetry_1 = require("../../utils/assertionHelpers/clickLocatorWithRetry");
const ConnectorMarketplacePage_1 = require("./ConnectorMarketplacePage");
class ModelerCreatePage {
    page;
    generalPanel;
    deployDiagramDialog;
    processIdInput;
    startEventElement;
    appendTaskButton;
    changeTypeButton;
    userTaskOption;
    appendEndEventButton;
    startInstanceMainButton;
    startInstanceSubButton;
    viewProcessInstanceLink;
    nameInput;
    diagramBreadcrumb;
    renameDiagramNameButton;
    diagramNameInput;
    variableInput;
    embedFormButton;
    embedButton;
    newForm;
    deploySubButton;
    deployMenuItem;
    additionalActionsButton;
    cancelButton;
    restConnectorOption;
    webhookMessageStartEventConnectorOption;
    webhookTab;
    webhookIsActiveButton;
    copyWebhookUrlToClipboardButton;
    createTask;
    createEndEvent;
    canvas;
    endEventCanvas;
    connectToOtherElementButton;
    firstPlacedElement;
    secondPlacedElement;
    appendElementButton;
    payloadInput;
    marketPlaceButton;
    publicHolidayConnectorOption;
    publicHolidayYearOption;
    publicHolidayCountryCodeOption;
    implementationSection;
    implementationOptions;
    intermediateBoundaryEvent;
    intermediateWebhookConnectorOption;
    correlationKeyProcessInput;
    correlationKeyPayloadInput;
    firstElement;
    secondElement;
    thirdElement;
    payloadNameInput;
    payloadNumberInput;
    payloadCheckboxInput;
    payloadDateInput;
    form;
    formPropertySection;
    formLinkingTypeDropdown;
    formLinkTypeOptions;
    addFormJsonConfigurationInput;
    publicationSection;
    publicAccessToggle;
    publicationTab;
    copyPublicLinkButton;
    closeButton;
    rbaEnabledDeployedDialog;
    viewProcessLink;
    appendGatewayButton;
    parallelGatewayOption;
    firstPlacedGateway;
    secondPlacedGateway;
    serviceTaskOption;
    taskDefinitionPanel;
    jobTypeInput;
    playTab;
    continueToPlayButton;
    assigneeInput;
    candidateGroupsInput;
    candidateUsersInput;
    assignmentSection;
    priorityInput;
    startEventVariableInputWithThreeVariables;
    zeebeRestAddressVariable;
    variableAssignmentValueTextbox;
    zeebeSecretVariable;
    variableAssignmentValueTextboxSecondVariable;
    zeebeClientIdVariable;
    variableAssignmentValueTextboxThirdVariable;
    connectorsDocHandlingStartEventElement;
    timerEventOption;
    timerEventSettings;
    timerType;
    timerValue;
    eighthPlacedElement;
    deployAndRunMainButton;
    deployAndRunSubButton;
    dialog;
    backupDeployButton;
    formLinkedSuccessMessage;
    webhookActiveMessage;
    diagramNameBreadcrumb;
    constructor(page) {
        this.page = page;
        this.generalPanel = page.locator('[data-group-id="group-general"]');
        this.processIdInput = 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.changeTypeButton = page.getByRole('button', {
            name: 'Change element',
            exact: true,
        });
        this.userTaskOption = page
            .getByRole('listitem', { name: 'User task' })
            .locator('span')
            .first();
        this.priorityInput = page.getByRole('textbox', { name: 'priority' });
        this.appendEndEventButton = page.getByTitle('Append end event');
        this.startInstanceMainButton = this.startInstanceMainButton = page
            .getByTitle('Deploys the current process (if not already deployed) and starts a new instance')
            .first();
        this.dialog = page.getByRole('dialog');
        this.deployAndRunMainButton = page.getByRole('button', {
            name: 'Deploy & run',
            exact: true,
        });
        this.deployAndRunSubButton = this.dialog.getByRole('button', {
            name: 'Deploy & run',
            exact: true,
        });
        this.startInstanceSubButton = page
            .getByRole('button', { name: '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('[id="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.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',
        })
            .first();
        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.secondPlacedElement = page.locator('g:nth-child(2) > .djs-element > .djs-hit');
        this.payloadInput = page.locator('[class="fjs-input"]');
        this.marketPlaceButton = page.getByTitle('Browse Marketplace for more Connectors');
        this.publicHolidayConnectorOption = page.getByRole('listitem', {
            name: 'Worldwide Public Holiday',
            exact: true,
        });
        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.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.form = page.locator('[class="fjs-container"]');
        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.processIdInput = page.getByLabel('ID', { exact: true });
        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.closeButton = page
            .getByRole('dialog')
            .getByRole('button', { name: 'Close' });
        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.rbaEnabledDeployedDialog = page.getByRole('dialog', {
            name: 'Process successfully deployed',
        });
        this.deployDiagramDialog = page.getByRole('dialog', {
            name: 'Deploy diagram',
        });
        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.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.continueToPlayButton = page.getByRole('button', { name: 'Continue' });
        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.startEventVariableInputWithThreeVariables =
            page.getByText('Output mapping3');
        this.zeebeRestAddressVariable = page
            .locator('[data-test="properties-panel"]')
            .getByText('zeebeRestAdress');
        this.variableAssignmentValueTextbox = page.getByRole('textbox', {
            name: 'Variable assignment value',
        });
        this.zeebeSecretVariable = page
            .locator('[data-test="properties-panel"]')
            .getByText('zeebeSecret');
        this.variableAssignmentValueTextboxSecondVariable = page.locator('#bio-properties-panel-StartEvent_1-output-1-source div');
        this.zeebeClientIdVariable = page
            .locator('[data-test="properties-panel"]')
            .getByText('zeebeClientId');
        this.variableAssignmentValueTextboxThirdVariable = page.locator('#bio-properties-panel-StartEvent_1-output-2-source div');
        this.connectorsDocHandlingStartEventElement = page.locator('g:nth-child(5) > .djs-element > .djs-hit');
        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.additionalActionsButton = page.getByRole('button', {
            name: 'Additional actions',
        });
        this.deployMenuItem = page.getByRole('menuitem', {
            name: 'Deploy',
        });
        this.backupDeployButton = page.getByRole('button', {
            name: 'Deploy',
        });
        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.webhookActiveMessage = page.getByText('Webhook is active');
    }
    async clickSecondDeployButton() {
        await this.backupDeployButton.click({ timeout: 60000 });
    }
    async modelJobWorkerDiagram(processName, embedFrom = false, processId = '') {
        await (0, test_1.expect)(this.generalPanel).toBeVisible({
            timeout: 120000,
        });
        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.clickStartEventElement();
        }
        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 modelCamundaUserTaskDiagram(processName, processId = '', formName = '') {
        await (0, test_1.expect)(this.generalPanel).toBeVisible({
            timeout: 180000,
        });
        await this.enterDiagramName(processName);
        await (0, sleep_1.sleep)(15000);
        if (processId.length > 0) {
            await this.clickStartEventElement();
            await this.clickGeneralPropertiesPanel();
            await this.clickIdInput();
            await this.fillIdInput(processId);
            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 assignToCandidateGroup(taskName, candidateGroup, assignee) {
        await this.clickCanvas();
        await this.selectUserTask(taskName);
        await this.expandAssignmentSection();
        await this.clickCandidateGroupsInput();
        await this.fillCandidateGroupsInput(candidateGroup);
        if (assignee) {
            await this.clickAssigneeInput();
            await this.fillAssigneeInput(assignee);
        }
    }
    async assignToCandidateUser(taskName, candidateUser, assignee) {
        await this.clickCanvas();
        await this.selectUserTask(taskName);
        await this.expandAssignmentSection();
        await this.clickCandidateUsersInput();
        await this.fillCandidateUsersInput(candidateUser);
        if (assignee) {
            await this.clickAssigneeInput();
            await this.fillAssigneeInput(assignee);
        }
    }
    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 clickAssigneeInput() {
        await this.assigneeInput.click({ timeout: 60000 });
    }
    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 fillAssigneeInput(name) {
        await this.assigneeInput.fill(name, { timeout: 60000 });
        await this.page.waitForTimeout(1000);
    }
    async clickCandidateGroupsInput() {
        await this.candidateGroupsInput.click({ timeout: 60000 });
    }
    async fillCandidateGroupsInput(name) {
        await this.candidateGroupsInput.fill(name, { timeout: 60000 });
        await this.page.waitForTimeout(1000);
    }
    async clickCandidateUsersInput() {
        await this.candidateUsersInput.click({ timeout: 60000 });
    }
    async fillCandidateUsersInput(candidateUser) {
        await this.candidateUsersInput.fill(candidateUser, { timeout: 60000 });
        await this.page.waitForTimeout(1000);
    }
    async selectUserTask(userTask) {
        await this.page.locator(`[data-element-id="${userTask}"]`).click();
    }
    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 clickProcessIdInput() {
        await this.processIdInput.click({ timeout: 60000 });
    }
    async fillProcessIdInput(id) {
        await this.processIdInput.fill(id, { timeout: 60000 });
    }
    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 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 clickForm(name) {
        await this.page
            .locator(`[data-test="item-${name}"]`)
            .getByText(name)
            .click({ timeout: 90000 });
    }
    async clickUserTask(id) {
        const priorityUserTask = this.page.locator(`[data-element-id="${id}"]`);
        await priorityUserTask.click({ timeout: 60000 });
    }
    async clickAppendEndEventButton(parentElement) {
        try {
            await this.appendEndEventButton.click({ timeout: 120000 });
        }
        catch (error) {
            await this.page.reload();
            await (0, sleep_1.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 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 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 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.clickPriorityInput();
            await this.fillPriorityInput(priority.toString());
            await this.clickCanvas();
            priority += 25;
        }
    }
    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,
        });
        await this.selectCluster(clusterName);
        await this.clickDeploySubButtonWithRetry(clusterName);
        await (0, test_1.expect)(this.viewProcessLink).toBeVisible({ timeout: 30000 });
        await (0, test_1.expect)(this.viewProcessLink).toBeHidden({ timeout: 30000 });
    }
    async clickStartInstanceMainButton() {
        if (await this.startInstanceMainButton.isVisible({ timeout: 30000 })) {
            await this.startInstanceMainButton.click({ timeout: 30000 });
        }
        else {
            await this.deployAndRunMainButton.click({ timeout: 30000 }); //will be available from alpha7
        }
    }
    async clickStartInstanceSubButton() {
        if (await this.startInstanceSubButton.isVisible({ timeout: 30000 })) {
            await this.startInstanceSubButton.click({ timeout: 30000 });
        }
        else {
            await this.deployAndRunSubButton.click({ timeout: 30000 }); //will be available from alpha7
        }
    }
    async runProcessInstance(clusterName, variables = '', formVariables = {}, textToVisible = '') {
        const maxRetries = 10;
        const retryDelayMs = 20000;
        for (let attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                await this.clickStartInstanceMainButton();
                await this.selectCluster(clusterName);
                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 (formVariables.formName) {
                        await this.fillStartFormName(formVariables.formName);
                    }
                    if (formVariables.checkbox === 'true') {
                        await this.checkStartFormCheckbox();
                    }
                    if (formVariables.startDate) {
                        await this.fillStartFormDate(formVariables.startDate);
                    }
                    if (formVariables.startNumber) {
                        await this.fillStartFormNumber(formVariables.startNumber);
                    }
                }
                if (textToVisible.length > 0) {
                    await (0, test_1.expect)(this.dialog.getByText(textToVisible)).toBeVisible({
                        timeout: 30000,
                    });
                }
                await this.clickStartInstanceSubButton();
                return;
            }
            catch (error) {
                console.warn(`Attempt ${attempt} failed: ${error instanceof Error ? error.message : error}`);
                if (attempt === maxRetries) {
                    throw new Error(`runProcessInstance failed after ${maxRetries} attempts.`);
                }
                await this.page.reload();
                await this.page.waitForTimeout(retryDelayMs);
            }
        }
    }
    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 clickViewProcessInstanceLink() {
        await this.viewProcessInstanceLink.click({ timeout: 180000 });
    }
    async clickNameInput() {
        await this.nameInput.click({ timeout: 60000 });
    }
    async fillNamedInput(name) {
        await this.nameInput.fill(name, { timeout: 60000 });
    }
    async clickDiagramBreadcrumb() {
        await this.diagramBreadcrumb.click({ timeout: 10000 });
    }
    async clickEditDiagramNameButton() {
        await this.renameDiagramNameButton.click({ timeout: 10000 });
    }
    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 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 clickWebhookStartEventConnectorOption() {
        await this.webhookMessageStartEventConnectorOption.click({ timeout: 60000 });
    }
    async clickWebhookTab() {
        await this.webhookTab.click({ timeout: 60000 });
    }
    async clickWebhookIsActiveButton() {
        await this.webhookIsActiveButton.click({ timeout: 60000 });
    }
    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 clickDeployButtonWithRetry(retries = 3) {
        for (let i = 0; i < retries; i++) {
            try {
                await this.clickAdditionalActionsButton();
                await this.clickDeployMenuItem();
                return;
            }
            catch (error) {
                console.error(`Attempt ${i + 1} to click deploy button failed: ${error}`);
                await this.page.reload();
                await (0, sleep_1.sleep)(10000);
            }
        }
        throw new Error(`Failed to click deploy button after ${retries} retries`);
    }
    async clickDeploySubButtonWithRetry(clusterName) {
        const retries = 3;
        for (let i = 0; i < retries; i++) {
            try {
                await test_1.expect
                    .poll(async () => {
                    try {
                        await (0, test_1.expect)(this.deploySubButton).toBeVisible({
                            timeout: 60000,
                        });
                        await this.deploySubButton.click({ force: true });
                        return true;
                    }
                    catch {
                        return false;
                    }
                }, { timeout: 30000, intervals: [1000, 2000] })
                    .toBe(true);
                await test_1.expect
                    .poll(async () => {
                    return !(await this.deployDiagramDialog.isVisible());
                }, { timeout: 180000, intervals: [2000, 5000] })
                    .toBe(true);
                return;
            }
            catch (error) {
                console.error(`Attempt ${i + 1} to click deploy sub button failed: ${error}`);
                await this.page.reload();
                await (0, sleep_1.sleep)(10000);
                await this.clickDeployButtonWithRetry();
                await this.selectCluster(clusterName);
            }
        }
        throw new Error(`Failed to click deploy sub 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 (0, test_1.expect)(this.connectToOtherElementButton).toBeVisible({
            timeout: 60000,
        });
        await this.connectToOtherElementButton.click({ timeout: 60000 });
    }
    async clickFirstPlacedElement() {
        await (0, test_1.expect)(this.firstPlacedElement).toBeVisible({ timeout: 60000 });
        await this.firstPlacedElement.click({ timeout: 60000 });
    }
    async clickSecondPlacedElement() {
        await this.secondPlacedElement.click({ timeout: 60000 });
    }
    async clickSecondElement() {
        await (0, test_1.expect)(this.secondElement).toBeVisible({ timeout: 60000 });
        await this.secondElement.click({ timeout: 60000 });
    }
    async clickAppendElementButton() {
        const maxRetries = 3;
        for (let retries = 0; retries < maxRetries; retries++) {
            try {
                await this.page.waitForTimeout(1000);
                await (0, test_1.expect)(this.appendElementButton).toBeVisible({ timeout: 10000 });
                await this.appendElementButton.hover({ force: true });
                return;
            }
            catch (error) {
                console.error(`Click attempt to append element ${retries + 1} failed: ${error}`);
            }
        }
        throw new Error(`Failed to hover append element after ${maxRetries} 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) {
                    // Re-download connector on second retry in case the first download failed
                    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.clickCanvas();
                    await this.secondElement.click({ timeout: 60000 });
                    await this.clickChangeTypeButton();
                }
                // Filter the virtualized change-element popup so the option scrolls into view
                const changeElementSearch = this.page.locator('.djs-popup-search input');
                if (await changeElementSearch
                    .isVisible({ timeout: 5000 })
                    .catch(() => false)) {
                    await changeElementSearch.pressSequentially('Worldwide Public Holiday', {
                        delay: 50,
                    });
                }
                await this.publicHolidayConnectorOption.waitFor({
                    state: 'visible',
                    timeout: 60000,
                });
                await this.publicHolidayConnectorOption.click({ timeout: 30000 });
                return;
            }
            catch (error) {
                console.error(`Click attempt ${retries + 1} failed: ${error}`);
                if (retries >= maxRetries - 1)
                    break;
                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) {
        await this.implementationSection.click();
        if ((await this.implementationOptions.inputValue()) == implementationType) {
            console.log(`${implementationType} is already selected.`);
        }
        else {
            await this.implementationOptions.selectOption(implementationType);
        }
        await this.assertImplementationOption(implementationType);
    }
    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 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 clickIdInput() {
        await this.processIdInput.click();
    }
    async fillIdInput(id) {
        await this.processIdInput.fill(id);
    }
    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 clickAppendGatewayButton() {
        await (0, test_1.expect)(this.appendGatewayButton).toBeVisible({ timeout: 30000 });
        await this.appendGatewayButton.click({ timeout: 30000 });
    }
    async clickParallelGatewayOption() {
        await (0, test_1.expect)(this.parallelGatewayOption).toBeVisible({ timeout: 30000 });
        await this.parallelGatewayOption.click({ timeout: 90000 });
    }
    async clickFirstPlacedGateway() {
        try {
            await this.firstPlacedGateway.click({ timeout: 60000 });
            await (0, test_1.expect)(this.appendElementButton).toBeVisible({ timeout: 60000 });
        }
        catch (error) {
            await this.page.reload();
            await (0, sleep_1.sleep)(10000);
            await this.firstPlacedGateway.click({ timeout: 60000 });
        }
    }
    async clickSecondPlacedGateway(userTaskId = '') {
        try {
            await this.secondPlacedGateway.click({ timeout: 60000 });
        }
        catch (error) {
            await this.page.reload();
            await (0, sleep_1.sleep)(10000);
            if (userTaskId != '') {
                await this.clickUserTask(userTaskId);
                await this.clickConnectToOtherElementButton();
            }
            await this.secondPlacedGateway.click({ timeout: 60000 });
        }
    }
    async addParallelUserTasks(numberOfTasks, taskName) {
        try {
            await this.clickAppendElementButton();
        }
        catch (error) {
            await this.page.reload();
            await (0, sleep_1.sleep)(20000);
            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.fillNamedInput(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.fillNamedInput(taskName + i);
            await this.clickIdInput();
            await this.fillIdInput(taskName + i);
            await this.clickUserTask(taskName + '1');
            await this.clickConnectToOtherElementButton();
            await this.clickSecondPlacedGateway(taskName + i);
            await this.clickCanvas();
            await (0, sleep_1.sleep)(1000);
        }
        await this.clickSecondPlacedGateway();
    }
    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;
        // New flow (8.10+): "Setup environment" panel with three steps:
        //   1. Connect cluster → "Configure environment" modal → select cluster → Save
        //   2. Deploy process → wait for success banner
        //   3. Configure scenario
        const setupDeployButton = this.page
            .getByText('Deploy process')
            .locator('..')
            .getByRole('button', { name: 'Deploy' });
        const configureScenarioButton = this.page.getByRole('button', {
            name: 'Configure scenario',
        });
        // Wait up to 15s for EITHER the new-flow setup panel OR the legacy Continue
        // button to appear. Using .or() avoids separate sequential timeouts that would
        // both expire before the page finishes loading on a slow cluster.
        const setupOrContinue = setupDeployButton.or(this.continueToPlayButton);
        const panelAppeared = await setupOrContinue
            .first()
            .isVisible({ timeout: 15000 })
            .catch(() => false);
        if (!panelAppeared) {
            // Neither appeared — Play is already configured and ready.
            return;
        }
        const isNewFlow = await setupDeployButton.isVisible().catch(() => false);
        if (isNewFlow) {
            // Step 1: connect cluster if not yet connected (modal with cluster dropdown)
            const connectClusterButton = this.page.getByRole('button', {
                name: 'Connect cluster',
            });
            const needsConnect = await connectClusterButton
                .isVisible({ timeout: 3000 })
                .catch(() => false);
            if (needsConnect) {
                await connectClusterButton.click({ timeout });
                const configureEnvDialog = this.page
                    .getByRole('dialog')
                    .filter({ hasText: 'Configure environment' });
                await (0, test_1.expect)(configureEnvDialog).toBeVisible({ timeout });
                // The "Configure environment" modal lists each available cluster as a
                // labelled toggle switch (cds--toggle), not as a combobox+option list.
                // Mirror the legacy `selectCluster` deploy-dialog logic: scope by the
                // cluster's label, toggle it on, and confirm the switch is checked
                // before saving. This handles environments with multiple clusters.
                const clusterLabel = configureEnvDialog
                    .locator('label')
                    .filter({ hasText: clusterName });
                const clusterSwitch = clusterLabel.getByRole('switch');
                await (0, test_1.expect)(clusterLabel).toBeVisible({ timeout });
                const alreadyChecked = (await clusterSwitch.getAttribute('aria-checked')) === 'true';
                if (!alreadyChecked) {
                    await clusterLabel.click({ timeout });
                }
                await (0, test_1.expect)(clusterSwitch).toBeChecked({ timeout });
                // Wait for "Healthy" status before saving so the deploy step
                // doesn't race the backend's health check.
                await (0, test_1.expect)(configureEnvDialog).toContainText('Healthy', {
                    timeout: 30000,
                });
                await configureEnvDialog
                    .getByRole('button', { name: 'Save' })
                    .click({ timeout });
            }
            // Step 2: deploy — wait for enabled; button stays disabled until the cluster
            // connection is confirmed by the backend after the Save in step 1.
            await (0, test_1.expect)(setupDeployButton).toBeEnabled({ timeout: 30000 });
            await setupDeployButton.click({ timeout });
            await (0, test_1.expect)(this.page.getByText('Process has been successfully deployed')).toBeVisible({ timeout: 90000 });
            // Step 3: configure scenario
            await configureScenarioButton.click({ timeout });
            return;
        }
        // Legacy flow: select cluster via dialog, then click Continue.
        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 embedForm(formName) {
        await this.clickEmbedFormButton();
        await this.clickForm(formName);
        await this.clickEmbedButton();
    }
    async fillStartEventVariablesForDocHandling(zeebeUrl, zeebeClientId, zeebeClientSecret) {
        console.log(`URL: ${zeebeUrl}, ClientId: ${zeebeClientId}, Secret: ${zeebeClientSecret}`);
        (0, test_1.expect)(this.connectorsDocHandlingStartEventElement).toBeVisible({
            timeout: 60000,
        });
        await this.connectorsDocHandlingStartEventElement.click();
        (0, test_1.expect)(this.startEventVariableInputWithThreeVariables).toBeVisible({
            timeout: 60000,
        });
        await this.startEventVariableInputWithThreeVariables.click();
        await this.fillZeebeRestValue(zeebeUrl);
        await this.fillZeebeSecretValue(zeebeClientSecret);
        await this.fillZeebeClientId(zeebeClientId);
        await (0, sleep_1.sleep)(1000);
    }
    async fillZeebeClientId(clientId) {
        await this.zeebeClientIdVariable.click();
        await (0, test_1.expect)(this.variableAssignmentValueTextboxThirdVariable).toBeVisible({
            timeout: 60000,
        });
        await this.variableAssignmentValueTextboxThirdVariable.click();
        await (0, sleep_1.sleep)(1000);
        await this.variableAssignmentValueTextboxThirdVariable.fill('');
        await this.variableAssignmentValueTextboxThirdVariable.fill(clientId);
        await (0, test_1.expect)(this.variableAssignmentValueTextboxThirdVariable).toHaveText(clientId);
    }
    async fillZeebeSecretValue(zeebeSecret) {
        await this.zeebeSecretVariable.click();
        await (0, test_1.expect)(this.variableAssignmentValueTextboxSecondVariable).toBeVisible({
            timeout: 60000,
        });
        await this.variableAssignmentValueTextboxSecondVariable.click();
        await (0, sleep_1.sleep)(1000);
        await this.variableAssignmentValueTextboxSecondVariable.fill('');
        await this.variableAssignmentValueTextboxSecondVariable.fill(zeebeSecret);
        await (0, test_1.expect)(this.variableAssignmentValueTextboxSecondVariable).toHaveText(zeebeSecret);
    }
    async fillZeebeRestValue(zeebeUrl) {
        await this.zeebeRestAddressVariable.click();
        await (0, test_1.expect)(this.variableAssignmentValueTextbox).toBeVisible({
            timeout: 60000,
        });
        await this.variableAssignmentValueTextbox.click();
        await (0, sleep_1.sleep)(1000);
        await this.variableAssignmentValueTextbox.fill('');
        await this.variableAssignmentValueTextbox.fill(zeebeUrl);
        await (0, test_1.expect)(this.variableAssignmentValueTextbox).toHaveText(zeebeUrl);
    }
    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 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: 15000,
            });
            console.log('Public access toggle enabled successfully');
        }
    }
    async clickPublicationTab() {
        await (0, clickLocatorWithRetry_1.clickLocatorWithRetry)(this.page, this.publicationTab, {
            postAction: async () => {
                await this.clickStartEventElement();
            },
        });
    }
    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 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;
