"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const applicationManagerPath = require("./ios-application-manager");
const fileSystemPath = require("./ios-device-file-system");
const commonConstants = require("../../../constants");
const constants = require("../../../../constants");
const net = require("net");
const decorators_1 = require("../../../decorators");
const helpers = require("../../../../common/helpers");
const ios_device_base_1 = require("../ios-device-base");
class IOSDevice extends ios_device_base_1.IOSDeviceBase {
    constructor(deviceActionInfo, $errors, $injector, $iOSDebuggerPortService, $deviceLogProvider, $lockService, $iOSSocketRequestExecutor, $processService, $devicePlatformsConstants, $iOSDeviceProductNameMapper, $iosDeviceOperations, $mobileHelper) {
        super();
        this.deviceActionInfo = deviceActionInfo;
        this.$errors = $errors;
        this.$injector = $injector;
        this.$iOSDebuggerPortService = $iOSDebuggerPortService;
        this.$deviceLogProvider = $deviceLogProvider;
        this.$lockService = $lockService;
        this.$iOSSocketRequestExecutor = $iOSSocketRequestExecutor;
        this.$processService = $processService;
        this.$devicePlatformsConstants = $devicePlatformsConstants;
        this.$iOSDeviceProductNameMapper = $iOSDeviceProductNameMapper;
        this.$iosDeviceOperations = $iosDeviceOperations;
        this.$mobileHelper = $mobileHelper;
        this.applicationManager = this.$injector.resolve(applicationManagerPath.IOSApplicationManager, { device: this, devicePointer: this.deviceActionInfo });
        this.fileSystem = this.$injector.resolve(fileSystemPath.IOSDeviceFileSystem, { device: this, devicePointer: this.deviceActionInfo });
        const productType = deviceActionInfo.productType;
        const isTablet = this.$mobileHelper.isiOSTablet(productType);
        const deviceStatus = deviceActionInfo.status || commonConstants.UNREACHABLE_STATUS;
        this.deviceInfo = {
            identifier: deviceActionInfo.deviceId,
            vendor: "Apple",
            platform: this.$devicePlatformsConstants.iOS,
            status: deviceStatus,
            errorHelp: deviceStatus === commonConstants.UNREACHABLE_STATUS ? `Device ${deviceActionInfo.deviceId} is ${commonConstants.UNREACHABLE_STATUS}` : null,
            type: "Device",
            isTablet: isTablet,
            displayName: this.$iOSDeviceProductNameMapper.resolveProductName(deviceActionInfo.deviceName) || deviceActionInfo.deviceName,
            model: this.$iOSDeviceProductNameMapper.resolveProductName(productType),
            version: deviceActionInfo.productVersion,
            color: deviceActionInfo.deviceColor,
            activeArchitecture: this.getActiveArchitecture(productType)
        };
    }
    get isEmulator() {
        return false;
    }
    openDeviceLogStream() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.deviceInfo.status !== commonConstants.UNREACHABLE_STATUS) {
                this._deviceLogHandler = this.actionOnDeviceLog.bind(this);
                this.$iosDeviceOperations.on(commonConstants.DEVICE_LOG_EVENT_NAME, this._deviceLogHandler);
                this.$iosDeviceOperations.startDeviceLog(this.deviceInfo.identifier);
            }
        });
    }
    getDebugSocketCore(appId) {
        const _super = name => super[name];
        return __awaiter(this, void 0, void 0, function* () {
            yield this.$iOSSocketRequestExecutor.executeAttachRequest(this, constants.AWAIT_NOTIFICATION_TIMEOUT_SECONDS, appId);
            const port = yield _super("getDebuggerPort").call(this, appId);
            const deviceId = this.deviceInfo.identifier;
            const socket = yield helpers.connectEventuallyUntilTimeout(() => __awaiter(this, void 0, void 0, function* () {
                const deviceResponse = _.first((yield this.$iosDeviceOperations.connectToPort([{ deviceId: deviceId, port: port }]))[deviceId]);
                const _socket = new net.Socket();
                _socket.connect(deviceResponse.port, deviceResponse.host);
                return _socket;
            }), commonConstants.SOCKET_CONNECTION_TIMEOUT_MS);
            return socket;
        });
    }
    actionOnDeviceLog(response) {
        if (response.deviceId === this.deviceInfo.identifier) {
            this.$deviceLogProvider.logData(response.message, this.$devicePlatformsConstants.iOS, this.deviceInfo.identifier);
        }
    }
    detach() {
        if (this._deviceLogHandler) {
            this.$iosDeviceOperations.removeListener(commonConstants.DEVICE_LOG_EVENT_NAME, this._deviceLogHandler);
        }
    }
    getActiveArchitecture(productType) {
        let activeArchitecture = "";
        if (productType) {
            productType = productType.toLowerCase().trim();
            const majorVersionAsString = productType.match(/.*?(\d+)\,(\d+)/)[1];
            const majorVersion = parseInt(majorVersionAsString);
            let isArm64Architecture = false;
            if (_.startsWith(productType, "iphone")) {
                isArm64Architecture = majorVersion >= 6;
            }
            else if (_.startsWith(productType, "ipad")) {
                isArm64Architecture = majorVersion >= 4;
            }
            else if (_.startsWith(productType, "ipod")) {
                isArm64Architecture = majorVersion >= 7;
            }
            activeArchitecture = isArm64Architecture ? "arm64" : "armv7";
        }
        return activeArchitecture;
    }
}
__decorate([
    decorators_1.cache()
], IOSDevice.prototype, "openDeviceLogStream", null);
exports.IOSDevice = IOSDevice;
$injector.register("iOSDevice", IOSDevice);
