"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.scrollExecutor = void 0;
const mablApi_1 = require("../../../mablApi");
const utilities_1 = require("../../utilities");
const contentActions_1 = require("../../background/capture/contentActions");
const boundingBoxUtils_1 = require("../../sharedUtils/boundingBoxUtils");
const DEFAULT_SCROLL_WAIT_TIME_MILLISECONDS = 1000;
exports.scrollExecutor = {
    needsFind: () => false,
    getStepType: () => mablApi_1.ExecuteToolName.Scroll,
    execute: async (payload, stateProvider, _eventHandler, logger) => {
        const toolParams = payload.toolCall.toolParams;
        if (!isScrollToolParams(toolParams)) {
            logger.error('Scroll executor requires valid scroll step parameters in payload');
            return {
                success: false,
                errorCause: 'IllegalArguments',
            };
        }
        const internalBoundingBox = toolParams.elementBoundingBox
            ? (0, boundingBoxUtils_1.convertToolLibraryBoundingBox)(toolParams.elementBoundingBox)
            : undefined;
        let scrollStatus;
        if (toolParams.direction === 'up') {
            scrollStatus = await (0, contentActions_1.sendScrollUpMessage)(stateProvider.getTrainingContext(), toolParams.scrollFactor, toolParams.elementTargetPoint, internalBoundingBox);
        }
        else if (toolParams.direction === 'down') {
            scrollStatus = await (0, contentActions_1.sendScrollDownMessage)(stateProvider.getTrainingContext(), toolParams.scrollFactor, toolParams.elementTargetPoint, internalBoundingBox);
        }
        else {
            logger.error(`Unknown scroll direction (${toolParams.direction}) in scroll executor`);
            return {
                success: false,
                errorCause: 'IllegalArguments',
            };
        }
        await (0, utilities_1.sleep)(DEFAULT_SCROLL_WAIT_TIME_MILLISECONDS);
        return {
            success: scrollStatus?.success ?? false,
            successDetail: {
                scrolledDistance: scrollStatus?.scrolledDistance ?? 0,
            },
            errorCause: scrollStatus?.success ? undefined : 'RecordFailed',
        };
    },
};
function isScrollToolParams(toolParams) {
    return (toolParams &&
        (toolParams.direction === 'up' || toolParams.direction === 'down'));
}
