"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const FindStrategy_1 = require("../actions/find/strategies/FindStrategy");
const webViewUtil_1 = require("../util/webViewUtil");
const ElementContextSwitcher_1 = __importDefault(require("./ElementContextSwitcher"));
const async_retry_1 = __importDefault(require("async-retry"));
class iOSElementContextSwitcher extends ElementContextSwitcher_1.default {
    async switchToElementContext(context) {
        if (context.contextType === FindStrategy_1.MobileContextType.native) {
            return this.switchToNativeContext();
        }
        if (context.contextType !== FindStrategy_1.MobileContextType.iOSWebView) {
            throw new Error(`Unsupported element context type: ${context.contextType}`);
        }
        return this.driver.switchContext(context.webViewId);
    }
    async switchToCorrectWebview(descriptor) {
        await this.waitForWebViewContextLoaded();
        return (0, async_retry_1.default)(async () => {
            const contexts = await (0, webViewUtil_1.getIOSWebViewContexts)(this.driver);
            for (const context of contexts) {
                if ((0, webViewUtil_1.doesWebviewMatch)(context.url, descriptor.webView.url)) {
                    await this.driver.switchContext(context.id);
                    return context.id;
                }
            }
            throw new Error(`Could not find WebView context with the URL: ${descriptor.webView.url}`);
        }, this.getAsyncRetryOptions());
    }
    async waitForWebViewContextLoaded() {
        if (!(await (0, webViewUtil_1.waitForWebViewContextLoaded)(this.driver))) {
            throw new Error(webViewUtil_1.NO_WEBVIEW_CONTEXT_FOUND);
        }
    }
}
exports.default = iOSElementContextSwitcher;
