"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IOSSocketRequestExecutor = void 0;
const constants = require("../../common/constants");
const yok_1 = require("../../common/yok");
class IOSSocketRequestExecutor {
    constructor($errors, $iOSNotification, $iOSNotificationService) {
        this.$errors = $errors;
        this.$iOSNotification = $iOSNotification;
        this.$iOSNotificationService = $iOSNotificationService;
    }
    async executeAttachRequest(device, timeout, appId) {
        const deviceId = device.deviceInfo.identifier;
        const mainRequestName = this.$iOSNotification.getAttachRequest(appId, deviceId);
        const readyRequestName = this.$iOSNotification.getReadyForAttach(appId);
        await this.executeRequest(mainRequestName, readyRequestName, appId, deviceId, timeout);
    }
    async executeRefreshRequest(device, timeout, appId) {
        const deviceId = device.deviceInfo.identifier;
        const mainRequestName = this.$iOSNotification.getRefreshRequest(appId);
        const refreshRequestStartedName = this.$iOSNotification.getAppRefreshStarted(appId);
        const result = await this.executeRequest(mainRequestName, refreshRequestStartedName, appId, deviceId, timeout);
        return result;
    }
    async executeRequest(mainRequestName, successfulyExecutedNotificationName, appId, deviceId, timeout) {
        let isSuccessful = false;
        try {
            const socket = await this.$iOSNotificationService.postNotification(deviceId, successfulyExecutedNotificationName, constants.IOS_OBSERVE_NOTIFICATION_COMMAND_TYPE);
            const notificationPromise = this.$iOSNotificationService.awaitNotification(deviceId, +socket, timeout);
            await this.$iOSNotificationService.postNotification(deviceId, mainRequestName);
            await notificationPromise;
            isSuccessful = true;
        }
        catch (e) {
            this.$errors.fail(`The application ${appId} does not appear to be running on ${deviceId} or is not built with debugging enabled. Try starting the application manually.`);
        }
        return isSuccessful;
    }
}
exports.IOSSocketRequestExecutor = IOSSocketRequestExecutor;
yok_1.injector.register("iOSSocketRequestExecutor", IOSSocketRequestExecutor);
