"use strict";
var byline = require("byline");
var device_android_debug_bridge_1 = require("./device-android-debug-bridge");
var LogcatHelper = (function () {
    function LogcatHelper($childProcess, $deviceLogProvider, $devicePlatformsConstants, $logger, $injector, $processService) {
        this.$childProcess = $childProcess;
        this.$deviceLogProvider = $deviceLogProvider;
        this.$devicePlatformsConstants = $devicePlatformsConstants;
        this.$logger = $logger;
        this.$injector = $injector;
        this.$processService = $processService;
        this.mapDeviceToLoggingStarted = Object.create(null);
    }
    LogcatHelper.prototype.start = function (deviceIdentifier) {
        var _this = this;
        if (deviceIdentifier && !this.mapDeviceToLoggingStarted[deviceIdentifier]) {
            var adb = this.$injector.resolve(device_android_debug_bridge_1.DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
            adb.executeCommand(["logcat", "-c"]).wait();
            var adbLogcat = adb.executeCommand(["logcat"], { returnChildProcess: true }).wait();
            var lineStream = byline(adbLogcat.stdout);
            adbLogcat.stderr.on("data", function (data) {
                _this.$logger.trace("ADB logcat stderr: " + data.toString());
            });
            adbLogcat.on("close", function (code) {
                try {
                    _this.mapDeviceToLoggingStarted[deviceIdentifier] = false;
                    if (code !== 0) {
                        _this.$logger.trace("ADB process exited with code " + code.toString());
                    }
                }
                catch (err) {
                }
            });
            lineStream.on('data', function (line) {
                var lineText = line.toString();
                _this.$deviceLogProvider.logData(lineText, _this.$devicePlatformsConstants.Android, deviceIdentifier);
            });
            this.$processService.attachToProcessExitSignals(this, adbLogcat.kill);
            this.mapDeviceToLoggingStarted[deviceIdentifier] = true;
        }
    };
    return LogcatHelper;
}());
exports.LogcatHelper = LogcatHelper;
$injector.register("logcatHelper", LogcatHelper);
