"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 });
class AndroidDebugBridge {
    constructor($childProcess, $errors, $logger, $staticConfig, $androidDebugBridgeResultHandler) {
        this.$childProcess = $childProcess;
        this.$errors = $errors;
        this.$logger = $logger;
        this.$staticConfig = $staticConfig;
        this.$androidDebugBridgeResultHandler = $androidDebugBridgeResultHandler;
    }
    executeCommand(args, options) {
        return __awaiter(this, void 0, void 0, function* () {
            let event = "close";
            const command = yield this.composeCommand(args);
            let treatErrorsAsWarnings = false;
            let childProcessOptions = undefined;
            if (options) {
                event = options.fromEvent || event;
                treatErrorsAsWarnings = options.treatErrorsAsWarnings;
                childProcessOptions = options.childProcessOptions;
                if (options.returnChildProcess) {
                    return this.$childProcess.spawn(command.command, command.args);
                }
            }
            const result = yield this.$childProcess.spawnFromEvent(command.command, command.args, event, childProcessOptions, { throwError: false });
            const errors = this.$androidDebugBridgeResultHandler.checkForErrors(result);
            if (errors && errors.length > 0) {
                this.$androidDebugBridgeResultHandler.handleErrors(errors, treatErrorsAsWarnings);
            }
            return (result.stdout === undefined || result.stdout === null) ? result : result.stdout;
        });
    }
    composeCommand(params, identifier) {
        return __awaiter(this, void 0, void 0, function* () {
            const command = yield this.$staticConfig.getAdbFilePath();
            let deviceIdentifier = [];
            if (identifier) {
                deviceIdentifier = ["-s", `${identifier}`];
            }
            const args = deviceIdentifier.concat(params);
            return { command, args };
        });
    }
}
exports.AndroidDebugBridge = AndroidDebugBridge;
$injector.register("adb", AndroidDebugBridge);
