"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findLogger = void 0;
exports.shouldListenForTrainedStepInRecording = shouldListenForTrainedStepInRecording;
exports.isTrustedEvent = isTrustedEvent;
exports.getPathOnEvent = getPathOnEvent;
exports.getCustomTestIdAttributes = getCustomTestIdAttributes;
exports.createEventMessageWithAncestor = createEventMessageWithAncestor;
exports.isPromise = isPromise;
exports.isWalkthroughTarget = isWalkthroughTarget;
const stateUtils_1 = require("../stateUtils");
const dom_util_1 = require("@mablhq-internal/mablscript-find/dom-util");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const browser_1 = require("@mablhq-internal/mablscript-find/browser");
const domUtils_1 = require("../../sharedUtils/domUtils");
const recording_1 = require("../recording");
const walkthrough_1 = require("../../sharedUtils/walkthrough");
exports.findLogger = new mablscriptFind_1.Logger();
const INCLUDE_APP_STATE = true;
const INCLUDE_OTHER_ATTRIBUTES = true;
function shouldListenForTrainedStepInRecording(state) {
    return (0, stateUtils_1.shouldListenForTrainedStep)(state);
}
function isTrustedEvent(event) {
    return event.isTrusted;
}
function getPathOnEvent(event) {
    return event.composedPath() ?? [];
}
function getCustomTestIdAttributes() {
    return recording_1.store.getState().training.configuration.customTestIdAttributes;
}
async function createEventMessageWithAncestor(target, action, listener, xPath, sourceEventTimeStamp) {
    const selectorPrototype = (0, dom_util_1.createBaseEventMessage)(target, action, listener, xPath, undefined, INCLUDE_APP_STATE, INCLUDE_OTHER_ATTRIBUTES, getCustomTestIdAttributes());
    const selectorSearchResult = (0, browser_1.createFindOneSelector)(target, exports.findLogger);
    const { chosenElementSelectorCandidate, chosenGroupSelectorCandidate } = selectorSearchResult;
    const shadowRootDocument = (0, mablscriptFind_1.maybeGetShadowRootHostFromElement)(target)?.shadowRoot;
    let promptSelectionIntent = false;
    let selectionRepeats = [];
    if (chosenGroupSelectorCandidate?.selector) {
        selectionRepeats = await (0, domUtils_1.getSelectionRepeats)(chosenGroupSelectorCandidate.selector, shadowRootDocument ?? undefined);
        if (selectionRepeats.length) {
            promptSelectionIntent = true;
        }
    }
    return {
        type: 'find_one',
        action,
        listener,
        elementSelectors: chosenElementSelectorCandidate?.selector,
        selectorPrototype,
        sourceEventTimeStamp,
        xPath,
        selectorSearchResult: {
            ...selectorSearchResult,
            promptSelectionIntent,
            selectionRepeats,
            targetType: 'element',
        },
    };
}
function isPromise(p) {
    return p && typeof p.then === 'function';
}
function isWalkthroughTarget(target) {
    return !!target?.attributes?.[walkthrough_1.WALKTHROUGH_TARGET_ATTRIBUTE];
}
