"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.humanizeEnterTextStep = humanizeEnterTextStep;
exports.enterTextStepToAIString = enterTextStepToAIString;
const StepWithFind_1 = __importStar(require("./StepWithFind"));
const yaml_utils_1 = require("../yaml-utils");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const variable_names_util_1 = require("../../variable-names-util");
const mablscript_step_types_1 = require("../../mablscript-step-types");
const BaseStep_1 = require("./BaseStep");
const type_utils_1 = require("../../type-utils");
const MablSymbol_1 = require("@mablhq/test-model/MablSymbol");
const MablscriptImporterUtil_1 = require("../MablscriptImporterUtil");
class EnterTextStep extends StepWithFind_1.default {
    static getStepType() {
        return mablscript_step_types_1.StepType.ENTER_TEXT;
    }
    constructor(findDescriptor, inputValue, variable, findOptions, flags = {}) {
        super(EnterTextStep.getStepType(), findDescriptor, findOptions);
        this.inputValue = inputValue;
        this.variable = variable;
        this.canBeCollapsed = true;
        this.options = {
            editable: true,
        };
        this.enterTextMode = flags.enterTextMode;
        if (flags.doNotRetry === true) {
            this.doNotRetry = true;
        }
    }
    isCollapsible(previousStep) {
        if (previousStep instanceof EnterTextStep &&
            !previousStep.isInsertVariable() &&
            !this.isInsertVariable()) {
            const targetElementSelector = this.getTargetElementSelector();
            const previousTargetElementSelector = previousStep.getTargetElementSelector();
            if (targetElementSelector && previousTargetElementSelector) {
                if ((0, mablscriptFind_1.buildElementSelectorString)(targetElementSelector) ===
                    (0, mablscriptFind_1.buildElementSelectorString)(previousTargetElementSelector)) {
                    return true;
                }
            }
        }
        return false;
    }
    isInsertVariable() {
        return this.variable?.name;
    }
    mergePreviousStep() { }
    generateMablscript() {
        const textInput = this.isInsertVariable() ?? `"${(0, mablscriptFind_1.escapeMablscriptString)(this.inputValue)}"`;
        const options = this.serializeOptions();
        return `${this.findDescriptorToMablscript()}.enter_text(${textInput}${options})`;
    }
    serializeOptions() {
        const parts = [];
        if (this.enterTextMode !== undefined) {
            parts.push(`enter_text_mode: "${this.enterTextMode}"`);
        }
        if (this.doNotRetry === true) {
            parts.push('do_not_retry: true');
        }
        return parts.length > 0 ? `, {${parts.join(', ')}}` : '';
    }
    inputVariables() {
        const findInputs = super.inputVariables();
        const inputValueInputs = this.isInsertVariable()
            ? [this.variable?.name ?? '']
            : (0, variable_names_util_1.extractVariableNamesFromPattern)(this.inputValue?.toString());
        return (0, type_utils_1.distinct)(findInputs.concat(inputValueInputs));
    }
    static generateStepFromMablStep(mablEnterTextStep, importer) {
        const { findDescriptor, findOptions } = this.getFindDescriptorAndFindOptions(mablEnterTextStep, importer);
        if ((0, mablscriptFind_1.isCustomFindDescriptor)(findDescriptor) ||
            (0, mablscriptFind_1.isFindOneDescriptor)(findDescriptor)) {
            const { inputValue, maybeVariable } = maybeGetVariableAndValue(mablEnterTextStep.text, importer);
            const descriptor = mablEnterTextStep.descriptor;
            return new EnterTextStep(findDescriptor, inputValue, maybeVariable, findOptions, {
                enterTextMode: descriptor.enterTextMode,
                doNotRetry: descriptor.doNotRetry,
            });
        }
        throw new Error('Invalid FindDescriptor found for Enter Text Step');
    }
}
exports.default = EnterTextStep;
function maybeGetVariableAndValue(textOrMablSymbol, importer) {
    let maybeVariable;
    let inputValue;
    if ((0, MablSymbol_1.isMablSymbolObject)(textOrMablSymbol)) {
        maybeVariable = (0, BaseStep_1.resolveVariableValue)(textOrMablSymbol.name, importer.variables);
        if (maybeVariable) {
            inputValue = maybeVariable.value;
        }
        else {
            const { value } = (0, MablscriptImporterUtil_1.resolveVariableOrValue)((0, MablSymbol_1.formatSymbol)(textOrMablSymbol), importer.variables);
            inputValue = value;
        }
    }
    else {
        const { value, variable } = (0, MablscriptImporterUtil_1.resolveVariableOrValue)(textOrMablSymbol, importer.variables);
        inputValue = value;
        maybeVariable = variable;
    }
    return { inputValue, maybeVariable };
}
function humanizeEnterTextStep(step) {
    const inputValueStr = step.inputValue?.toString() ?? '';
    if (step.variable?.name || (0, mablscriptFind_1.isLoneVariablePattern)(inputValueStr)) {
        return humanizeInsertVariableDescriptor(step, inputValueStr);
    }
    return humanizeEnterText(step);
}
function humanizeInsertVariableDescriptor(step, inputValueStr) {
    let varDisplay;
    if (step.variable) {
        varDisplay = step.variable.humanizedName || step.variable.name;
    }
    else if ((0, mablscriptFind_1.isLoneVariablePattern)(inputValueStr)) {
        const rawVarName = (0, mablscriptFind_1.getVariableNameFromLoneVariablePattern)(inputValueStr) ?? '';
        varDisplay = (0, mablscriptFind_1.removeUserNamespace)(rawVarName);
    }
    else {
        varDisplay = inputValueStr;
    }
    return `Insert value of variable "${varDisplay}" into ${(0, StepWithFind_1.humanizeFind)(step)}`;
}
function humanizeEnterText(step) {
    const inputValue = (0, StepWithFind_1.isPasswordField)(step)
        ? 'a password'
        : (0, mablscriptFind_1.humanizeText)(step.inputValue?.toString() ?? '');
    return `Enter ${inputValue} in ${(0, StepWithFind_1.humanizeFind)(step)}`;
}
function enterTextStepToAIString(step) {
    const isPassword = (0, StepWithFind_1.isPasswordField)(step);
    const result = {
        stepType: step.stepType,
        target: (0, StepWithFind_1.findDescriptorToAIObject)(step.findDescriptor, step.findOptions),
    };
    if (step.variable?.name) {
        result.variable = step.variable.humanizedName || step.variable.name;
    }
    else if (isPassword) {
        result.text = '***';
        result.is_password = true;
    }
    else {
        result.text = step.inputValue?.toString();
    }
    return (0, yaml_utils_1.toYaml)(result);
}
