"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrepareSessionExecutor = void 0;
exports.getAppInstallPathFromActiveSessions = getAppInstallPathFromActiveSessions;
const execution_1 = require("@mablhq-internal/runtime/execution");
const execution_2 = require("@mablhq-internal/runtime/execution");
const InstallAppExecutor_1 = require("./InstallAppExecutor");
const UninstallAppExecutor_1 = require("./UninstallAppExecutor");
const mobileUtil_1 = require("../util/mobileUtil");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
class PrepareSessionExecutor {
    run(step, executionContext) {
        return (0, execution_1.runActionWithElementReadyRetriesForMobile)(() => this.prepareSession(step, executionContext), executionContext);
    }
    async prepareSession(_step, executionContext) {
        const driver = executionContext.mobileTestEnvironment.getDriver();
        let appPath = executionContext.mobileTestEnvironment.getConfig().app.path;
        if (executionContext.mobileTestEnvironment.getConfig()
            .cloudTrainingConfiguration) {
            appPath =
                (await getAppInstallPathFromActiveSessions(driver)) ??
                    executionContext.mobileTestEnvironment.getCloudTrainingAndroidAppPath();
        }
        if (!appPath) {
            return Promise.resolve({
                status: execution_2.StepStatus.Failed,
                logInfo: 'No app path supplied for installing the application during session preparation',
            });
        }
        const platform = executionContext.mobileTestEnvironment.getConfig().app.platformName;
        const isCloudRun = executionContext.testContext.isCloudRun;
        const executionIndex = executionContext.executionIndexTracker.getExecutionIndex();
        const isFirstStep = executionIndex.flowSourceIndex === 0 &&
            executionIndex.stepSourceIndex === 0;
        const isFirstStepInCloud = isFirstStep && isCloudRun;
        try {
            if (!isFirstStepInCloud) {
                const getAppUnderTestId = () => executionContext.mobileTestEnvironment.getAppUnderTestId();
                let appId = await getAppUnderTestId();
                if ((0, mobileUtil_1.isSystemApp)(appId)) {
                    try {
                        await (0, UninstallAppExecutor_1.dismissAlerts)(driver, platform, getAppUnderTestId);
                    }
                    catch (error) {
                        executionContext.log.warning(`Error dismissing alerts: ${error}`);
                    }
                    appId = await getAppUnderTestId();
                }
                if (appId) {
                    if (!(0, mobileUtil_1.isSystemApp)(appId)) {
                        const isAppInstalled = await driver.isAppInstalled(appId);
                        if (isAppInstalled) {
                            try {
                                await (0, UninstallAppExecutor_1.uninstallAppAction)(appId, driver, platform);
                                executionContext.log.info(`Uninstalled app - [${appId}]`);
                            }
                            catch (error) {
                                executionContext.log.error('Could not uninstall app during Prepare Session step', error);
                            }
                        }
                    }
                    if (platform === mablApi_1.MobilePlatformEnum.Ios &&
                        !executionContext.mobileTestEnvironment.getConfig().app.isRealDevice) {
                        executionContext.log.info('Clearing iOS simulator keychains');
                        try {
                            await driver.execute('mobile: clearKeychains');
                        }
                        catch (error) {
                            executionContext.log.error(`unable to clear keychain on simulator`, error);
                        }
                    }
                    await (0, InstallAppExecutor_1.installAppAction)(appPath, appId, driver, platform);
                    executionContext.log.info(`Installed app - [${appId}]`);
                }
            }
            else {
                executionContext.log.info('Cloud run detected, skipping app uninstall/install');
            }
            try {
                const appUnderTestId = await executionContext.mobileTestEnvironment.getAppUnderTestId();
                executionContext.log.info(`App under test ID: [${appUnderTestId}]`);
            }
            catch (error) {
                executionContext.log.error('Unable to identify the app under test ID', error);
            }
            return {
                status: execution_2.StepStatus.Passed,
            };
        }
        catch (error) {
            executionContext.log.error(error);
            return Promise.resolve({
                status: execution_2.StepStatus.Failed,
                logInfo: `Error preparing the session`,
            });
        }
    }
}
exports.PrepareSessionExecutor = PrepareSessionExecutor;
async function getAppInstallPathFromActiveSessions(driver) {
    const capabilities = (await driver.getAppiumSessionCapabilities());
    if (capabilities.app) {
        return capabilities.app;
    }
    if (capabilities['appium:app']) {
        return capabilities['appium:app'];
    }
    const driverCapabilities = driver.capabilities;
    if (!driverCapabilities) {
        return undefined;
    }
    if (driverCapabilities['appium:app']) {
        return driverCapabilities['appium:app'];
    }
    return driverCapabilities.app;
}
