"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapWdio = exports.WRAPPED_ELEMENT_METHODS = exports.WRAPPED_BROWSER_METHODS = exports.WdioController = void 0;
exports.wdioConfig = wdioConfig;
exports.wdioTestRunner = wdioTestRunner;
const fs_1 = __importDefault(require("fs"));
const Controller_1 = __importDefault(require("../Controller"));
const writeVariables_1 = __importDefault(require("../utils/writeVariables"));
const constantsNode_1 = require("../utils/constantsNode");
const headlessNotSupportedError_1 = require("../utils/headlessNotSupportedError");
const mergeChromeArgs_1 = __importDefault(require("../utils/mergeChromeArgs"));
const checkUserArgs_1 = require("../utils/checkUserArgs");
const writeSessionFile_1 = __importDefault(require("../utils/writeSessionFile"));
const noop = () => {
};
function wdioConfig({ axe, ...options }) {
    (0, writeVariables_1.default)(axe);
    const chromeOpts = options.capabilities?.['goog:chromeOptions'] || {};
    const args = chromeOpts.args || [];
    if (['headless', '--headless'].some(flag => args.includes(flag))) {
        throw new headlessNotSupportedError_1.HeadlessNotSupportedError(`In WebdriverIO, use "headless=new" instead of "headless" in the "args" property of your "${CHROME_OPTIONS}" browser capability configuration.`);
    }
    (0, checkUserArgs_1.checkUserArgs)(args);
    return {
        ...options,
        capabilities: {
            browserName: (options?.capabilities).browserName ?? 'chrome',
            ...options?.capabilities,
            'goog:chromeOptions': {
                ...chromeOpts,
                args: (0, mergeChromeArgs_1.default)(args, {
                    disableOtherExtensions: true,
                    disableLoadExtensionCommandFeature: true
                })
            }
        }
    };
}
const CHROME_OPTIONS = 'goog:chromeOptions';
function wdioTestRunner(...params) {
    let axe;
    let config;
    if (params.length === 1) {
        ;
        ({ axe, ...config } = params[0]);
    }
    else {
        ;
        [axe, config] = params;
    }
    (0, writeSessionFile_1.default)({ buildID: axe.buildID });
    (0, writeVariables_1.default)({ ...axe, isWdioTestrunner: true });
    const capabilities = config.capabilities || [
        { [CHROME_OPTIONS]: { args: [] } }
    ];
    const firstCapability = capabilities[0];
    firstCapability[CHROME_OPTIONS] = firstCapability[CHROME_OPTIONS] || {};
    const chromeOpts = firstCapability[CHROME_OPTIONS];
    chromeOpts.args = chromeOpts.args || [];
    const args = chromeOpts.args;
    if (['headless', '--headless'].some(flag => args.includes(flag))) {
        throw new headlessNotSupportedError_1.HeadlessNotSupportedError(`In WebdriverIO, use "headless=new" instead of "headless" in the "args" property of your "${CHROME_OPTIONS}" browser capability configuration.`);
    }
    (0, checkUserArgs_1.checkUserArgs)(args);
    chromeOpts.args = (0, mergeChromeArgs_1.default)(args, {
        disableOtherExtensions: false,
        disableLoadExtensionCommandFeature: true
    });
    const { onPrepare = noop, onComplete = noop } = config;
    return {
        ...config,
        capabilities,
        onPrepare(...prepareParams) {
            return onPrepare(...prepareParams);
        },
        onComplete(...completeParams) {
            try {
                fs_1.default.unlinkSync(constantsNode_1.PATH_TO_SESSION_FILE);
            }
            catch {
            }
            return onComplete(...completeParams);
        }
    };
}
class WdioController extends Controller_1.default {
    constructor(driver) {
        super({
            debugLoggerName: 'WdioController',
            integrationName: 'WDIO',
            configurationFunction: 'wdioConfig()'
        });
        this.driver = driver;
    }
    async executeScript(fn, ...args) {
        const script = `
      const callback = arguments[arguments.length - 1];
      Promise.resolve(...arguments)
        .then(${fn})
        .then(callback);
    `;
        const result = await this.driver.executeAsync(script, ...args);
        return result;
    }
    captureScreenshot() {
        return this.driver.takeScreenshot();
    }
}
exports.WdioController = WdioController;
exports.WRAPPED_BROWSER_METHODS = [
    'reloadSession',
    'setWindowSize',
    'switchWindow',
    'touchAction',
    'newWindow',
    'pause',
    'url',
    'waitUntil'
];
exports.WRAPPED_ELEMENT_METHODS = [
    'addValue',
    'clearValue',
    'click',
    'doubleClick',
    'dragAndDrop',
    'moveTo',
    'scrollIntoView',
    'setValue',
    'touchAction',
    'waitForClickable',
    'waitForDisplayed',
    'waitForEnabled',
    'waitForExist',
    'waitUntil'
];
const wrapWdio = (browser, controller) => {
    const wrapper = async (fn, ...args) => {
        const res = await fn(...args);
        await controller.analyze({ __UserRequestedAnalyze: false });
        return res;
    };
    for (const method of exports.WRAPPED_BROWSER_METHODS) {
        browser.overwriteCommand(method, wrapper);
    }
    for (const method of exports.WRAPPED_ELEMENT_METHODS) {
        browser.overwriteCommand(method, wrapper, true);
    }
    return browser;
};
exports.wrapWdio = wrapWdio;
//# sourceMappingURL=wdio.js.map