"use strict";
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 virtual_device_1 = require("../mobile-base/virtual-device");
const DeviceSignals_1 = require("../enums/DeviceSignals");
const android_controller_1 = require("../android-controller");
const utils_1 = require("../utils");
const child_process_1 = require("child_process");
class AndroidVirtualDevice extends virtual_device_1.VirtualDevice {
    constructor() { super(); }
    startDevice(device) {
        return __awaiter(this, void 0, void 0, function* () {
            const startedDevice = yield android_controller_1.AndroidController.startEmulator(device);
            this._deviceProcess = startedDevice.process;
            this._device = startedDevice;
            this._checkEmulatorState = setInterval(() => {
                if (android_controller_1.AndroidController.getCurrentFocusedScreen(this._device).trim() === "") {
                    this.stopDevice();
                }
            }, 30000);
            this.emit(DeviceSignals_1.DeviceSignal.onDeviceStartedSignal, this._device);
            return startedDevice;
        });
    }
    stopDevice() {
        android_controller_1.AndroidController.kill(this._device);
        this.onDeviceKilled(this._device);
    }
    attachToDevice(deviceInfo) {
        this._device = deviceInfo || this._device;
        this._respondProcess = child_process_1.spawn("adb", ["-s", `emulator-${this._device.token}`, 'logcat', '*:E'], {
            detached: true,
            stdio: ['pipe']
        });
        this._respondProcess.stdout.once("close" || "error" || "end", (data) => {
            const dataToLog = data.toString();
            console.log("stderr: ", dataToLog);
            this.emit(DeviceSignals_1.DeviceSignal.onDeviceErrorSignal, this._device);
        });
        if (!this._deviceProcess) {
            this._deviceProcess = this._respondProcess;
            super.subscribeForEvents();
        }
        this.emit(DeviceSignals_1.DeviceSignal.onDeviceAttachedSignal, deviceInfo);
    }
    onDeviceStarted(...args) {
        utils_1.logInfo(`Device has started successfully!!!`, args);
    }
    onDeviceError(...args) {
        utils_1.logError(args);
    }
    onDeviceKilled(...args) {
        android_controller_1.AndroidController.cleanLockFile(this._device);
        utils_1.logWarn("Killed: ", args);
        if (this._deviceProcess) {
            this._deviceProcess.kill("SIGTERM");
            this._deviceProcess.removeAllListeners();
        }
        if (this._checkEmulatorState) {
            clearInterval(this._checkEmulatorState);
            this._checkEmulatorState = null;
        }
    }
    stdout(...args) {
        console.log("stdout: ", args.toString());
    }
    stdin(...args) {
        console.log("stdin: ", args.toString());
    }
    onAttachToDevice(device) {
    }
}
exports.AndroidVirtualDevice = AndroidVirtualDevice;
// softsenov2:mobile-devices-controller tsenov$ ps aux | grep 'Android'
// tsenov           32233   0.0  0.0  4267768    900 s011  S+    5:33pm   0:00.00 grep Android
// tsenov           31898   0.0  0.3  4526504  52180   ??  S     5:23pm   0:01.43 /Users/tsenov/Library/Android/sdk/emulator/emulator64-crash-service -pipe com.google.AndroidEmulator.CrashService.31884 -ppid 31884 -data-dir /tmp/android-tsenov/9b503177-6ef1-4486-b837-9fc8dd0154bd
// mcsoftsenov2:mobile-devices-controller tsenov$
//# sourceMappingURL=android-virtual-device.js.map