"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 AndroidElementContextSwitcher extends ElementContextSwitcher_1.default {
    async switchToElementContext(context) {
        if (context.contextType === FindStrategy_1.MobileContextType.native) {
            return this.switchToNativeContext();
        }
        if (context.contextType !== FindStrategy_1.MobileContextType.androidWebView) {
            throw new Error(`Unsupported element context type: ${context.contextType}`);
        }
        await this.switchToWebViewContext();
        await this.driver.switchToWindow(context.windowHandle);
    }
    async switchToCorrectWebview(descriptor) {
        await this.switchToWebViewContext();
        return (0, async_retry_1.default)(async () => {
            const contexts = await (0, webViewUtil_1.getAndroidWebViewWindowHandles)(this.driver);
            for (const context of contexts) {
                if ((0, webViewUtil_1.doesWebviewMatch)(context.url, descriptor.webView.url)) {
                    await this.driver.switchToWindow(context.id);
                    return context.id;
                }
            }
            throw new Error(`Could not find WebView context with the URL: ${descriptor.webView.url}`);
        }, this.getAsyncRetryOptions());
    }
    async switchToWebViewContext() {
        const currentContext = await this.driver.getContext();
        const currentContextId = (0, webViewUtil_1.isDetailedContext)(currentContext)
            ? currentContext.id
            : currentContext;
        if (currentContextId.startsWith(webViewUtil_1.WEBVIEW_CONTEXT_PREFIX)) {
            return;
        }
        const webViewContextLoaded = await (0, webViewUtil_1.waitForWebViewContextLoaded)(this.driver);
        if (!webViewContextLoaded) {
            throw new Error(webViewUtil_1.NO_WEBVIEW_CONTEXT_FOUND);
        }
        const webViewContextId = await (0, webViewUtil_1.getAndroidWebViewContextId)(this.driver);
        if (webViewContextId === undefined) {
            throw new Error(webViewUtil_1.NO_WEBVIEW_CONTEXT_FOUND);
        }
        await this.driver.switchContext(webViewContextId);
    }
}
exports.default = AndroidElementContextSwitcher;
