"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.humanizeKeyPressStep = humanizeKeyPressStep;
exports.generateHumanizedKeys = generateHumanizedKeys;
exports.humanizeKeyInfo = humanizeKeyInfo;
exports.keyPressStepToAIString = keyPressStepToAIString;
const StepWithFind_1 = __importStar(require("./StepWithFind"));
const yaml_utils_1 = require("../yaml-utils");
const keyUtils_1 = require("../../keyUtils");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const BaseStep_1 = require("./BaseStep");
const mablscript_step_types_1 = require("../../mablscript-step-types");
class KeyPressStep extends StepWithFind_1.default {
    static getStepType() {
        return mablscript_step_types_1.StepType.KEYPRESS;
    }
    constructor(findDescriptor, keyInfoArray, findOptions) {
        super(KeyPressStep.getStepType(), findDescriptor, findOptions);
        this.keyInfoArray = keyInfoArray;
        this.canBeCollapsed = true;
        this.options = {
            editable: true,
        };
    }
    isCollapsible(previousStep) {
        return (previousStep instanceof KeyPressStep &&
            previousStep.getTargetElementSelector()?.xpath ===
                this.getTargetElementSelector()?.xpath &&
            !KeyPressStep.hasActiveModifiers(previousStep.keyInfoArray[0]) &&
            !KeyPressStep.hasActiveModifiers(this.keyInfoArray[0]));
    }
    mergePreviousStep(previousStep) {
        this.keyInfoArray = previousStep.keyInfoArray.concat(this.keyInfoArray);
        this.findDescriptor = previousStep.findDescriptor;
        this.sourceEventIdentifiers = previousStep.sourceEventIdentifiers.concat(this.sourceEventIdentifiers);
        this.sourceEventIdentifiers = this.sourceEventIdentifiers.splice(-1 * BaseStep_1.MAX_DOM_EVENT_IDENTIFIERS);
    }
    generateMablscript() {
        const argumentStrings = this.keyInfoArray.map((value) => (0, mablscriptFind_1.buildStepArgumentString)({ params: value, legacy: true }));
        return `${this.findDescriptorToMablscript()}.send_keys(${argumentStrings.join()})`;
    }
    static getActiveModifiers(keyInfo, includeOverrides) {
        const modifiers = KeyPressStep.getModifiers(keyInfo, includeOverrides);
        return Object.keys(modifiers).filter((k) => modifiers[k]);
    }
    static hasActiveModifiers(keyInfo) {
        return !!KeyPressStep.getActiveModifiers(keyInfo, false).length;
    }
    static getModifiers(keyInfo, includeOverrides) {
        const objectKeys = Object.keys(keyUtils_1.MODIFIER_KEY_IDENTIFIER_MAP);
        const pickKeys = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));
        let modifiers = pickKeys(keyInfo, objectKeys);
        if (includeOverrides) {
            modifiers = {
                ...modifiers,
                ...pickKeys(keyInfo, objectKeys.map((key) => `windows.${key}`)),
                ...pickKeys(keyInfo, objectKeys.map((key) => `mac.${key}`)),
            };
        }
        return modifiers;
    }
    static generateStepFromMablStep(mablSendKeyStep, importer) {
        const { findDescriptor, findOptions } = this.getFindDescriptorAndFindOptions(mablSendKeyStep, importer);
        if ((0, mablscriptFind_1.isCustomFindDescriptor)(findDescriptor) ||
            (0, mablscriptFind_1.isFindOneDescriptor)(findDescriptor)) {
            return new KeyPressStep(findDescriptor, mablSendKeyStep.keys, findOptions);
        }
        throw new Error('No FindDescriptor found for Key Press Step');
    }
}
exports.default = KeyPressStep;
function humanizeKeyPressStep(step) {
    const keypresses = generateHumanizedKeys(step);
    const pluralizedKeypress = step.keyInfoArray.length > 1 ? 'keypresses' : 'keypress';
    return `Send "${keypresses}" ${pluralizedKeypress} to ${(0, StepWithFind_1.humanizeFind)(step)}`;
}
function generateHumanizedKeys(step) {
    return step.keyInfoArray.map((key) => humanizeKeyInfo(step, key)).join('');
}
function humanizeKeyInfo(step, keyInfo) {
    if (!keyInfo) {
        return '';
    }
    const activeModifiers = KeyPressStep.getActiveModifiers(keyInfo, false);
    const activeModifierStrings = activeModifiers.map((modifierKey) => keyUtils_1.MODIFIER_KEY_HUMANIZED_MAP[modifierKey]);
    const hasActiveModifiers = (activeModifierStrings?.length ?? 0) > 0;
    const activeModifiersPrefix = hasActiveModifiers
        ? activeModifierStrings.join('+') + '+'
        : '';
    const hasMacOverride = keyInfo.mac?.key;
    const hasWindowsOverride = keyInfo.windows?.key;
    let humanizedString = `${activeModifiersPrefix}${generateHumanizedKey(step, keyInfo)}`;
    if (hasMacOverride || hasWindowsOverride) {
        humanizedString = `Default: ${humanizedString}`;
    }
    if (hasMacOverride) {
        humanizedString += `, Mac: ${humanizeKeyInfo(step, keyInfo.mac)}`;
    }
    if (hasWindowsOverride) {
        humanizedString += `, Windows: ${humanizeKeyInfo(step, keyInfo.windows)}`;
    }
    return humanizedString;
}
function generateHumanizedKey(step, keyInfo) {
    if ((0, keyUtils_1.keyIsSpecial)(keyInfo.key)) {
        return `[${keyInfo.key.toUpperCase()}]`;
    }
    return (0, StepWithFind_1.isPasswordField)(step) ? '*' : keyInfo.key;
}
function keyPressStepToAIString(step) {
    const isPassword = (0, StepWithFind_1.isPasswordField)(step);
    const keys = step.keyInfoArray.map((keyInfo) => {
        const keyObj = {
            key: isPassword ? '*' : keyInfo.key,
        };
        if (keyInfo.altKey) {
            keyObj.alt = true;
        }
        if (keyInfo.ctrlKey) {
            keyObj.ctrl = true;
        }
        if (keyInfo.metaKey) {
            keyObj.meta = true;
        }
        if (keyInfo.shiftKey) {
            keyObj.shift = true;
        }
        return keyObj;
    });
    const result = {
        stepType: step.stepType,
        keys,
        target: (0, StepWithFind_1.findDescriptorToAIObject)(step.findDescriptor, step.findOptions),
    };
    return (0, yaml_utils_1.toYaml)(result);
}
