"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pageReady = exports.whenBusyContextReady = exports.getBusyStates = void 0;
const selenium_webdriver_1 = require("selenium-webdriver");
const oj_module_proxy_1 = require("./oj-module-proxy");
/**
 * Get open busy state descriptions from the page context
 * @private
 * @param driver
 * @returns an array of strings of busy state descriptions
 */
const getBusyStates = async (driver) => {
    const hasProxy = await driver.executeScript(`return '${oj_module_proxy_1.TEST_OBJ_NAME}' in window`);
    if (hasProxy) {
        return (0, oj_module_proxy_1.executeWithModules)(driver, ['BusyContext'], [], '(BusyContext) => BusyContext.getBusyStates().map((state) => state.description)').catch((ex) => ex.message);
    }
    return '';
};
exports.getBusyStates = getBusyStates;
/**
 * Returns a Promise that is resolved when the application's busy
 * state reports ready or the page is not a JET page (RequireJS
 * or ojs/ojcontext module not available).
 * @private
 * @param driver WebDriver instance
 * @return A Promise which is resolved to true when the
 * page's busy state is ready or to false when it is not a JET page.
 */
const whenBusyContextReady = async (driver) => {
    return (0, oj_module_proxy_1.executeWithModules)(driver, ['BusyContext'], [], '(BusyContext) => BusyContext.whenReady()').catch(async (ex) => {
        if (ex instanceof selenium_webdriver_1.error.TimeoutError || ex instanceof selenium_webdriver_1.error.ScriptTimeoutError) {
            const openStates = await (0, exports.getBusyStates)(driver);
            throw Error(`BusyContext.whenReady() timed out: ${ex.message}\nBusy states: ${openStates}`);
        }
        else {
            // unexpected error which is just reported as a warning below
            return false;
        }
    });
};
exports.whenBusyContextReady = whenBusyContextReady;
/**
 * Create a Condition for WebDriver to wait on the page's BusyContext to be ready
 */
function pageReady() {
    return new selenium_webdriver_1.Condition('for JET page to indicate ready', async (driver) => {
        // Check that <html> element has a size after page ready
        // Call thru executeScript to bypass WebElement overrides
        const size = await driver.executeScript(`
      const html = document.querySelector('html');
      return { width: html.clientWidth, height: html.clientHeight }
    `);
        if (!(size.width && size.height)) {
            return Promise.resolve(false);
        }
        return (0, exports.whenBusyContextReady)(driver);
    });
}
exports.pageReady = pageReady;
//# sourceMappingURL=busy-context-utils.js.map