"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
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 os_1 = require("os");
var application_manager_base_1 = require("../application-manager-base");
var constants_1 = require("../../constants");
var Future = require("fibers/future");
var helpers_1 = require("../../helpers");
var AndroidApplicationManager = (function (_super) {
    __extends(AndroidApplicationManager, _super);
    function AndroidApplicationManager(adb, identifier, $staticConfig, $options, $logcatHelper, $androidProcessService, $httpClient, $logger, $hooksService) {
        _super.call(this, $logger, $hooksService);
        this.adb = adb;
        this.identifier = identifier;
        this.$staticConfig = $staticConfig;
        this.$options = $options;
        this.$logcatHelper = $logcatHelper;
        this.$androidProcessService = $androidProcessService;
        this.$httpClient = $httpClient;
    }
    AndroidApplicationManager.prototype.getInstalledApplications = function () {
        var _this = this;
        return (function () {
            var result = _this.adb.executeShellCommand(["pm", "list", "packages"]).wait() || "";
            var regex = /package:(.+)/;
            return result.split(os_1.EOL)
                .map(function (packageString) {
                var match = packageString.match(regex);
                return match ? match[1] : null;
            })
                .filter(function (parsedPackage) { return parsedPackage !== null; });
        }).future()();
    };
    AndroidApplicationManager.prototype.installApplication = function (packageFilePath) {
        return this.adb.executeCommand(["install", "-r", ("" + packageFilePath)]);
    };
    AndroidApplicationManager.prototype.uninstallApplication = function (appIdentifier) {
        return this.adb.executeShellCommand(["pm", "uninstall", ("" + appIdentifier)], { treatErrorsAsWarnings: true });
    };
    AndroidApplicationManager.prototype.startApplication = function (appIdentifier, framework) {
        var _this = this;
        return (function () {
            _this.adb.executeShellCommand(["monkey",
                "-p", appIdentifier,
                "-c", "android.intent.category.LAUNCHER",
                "1"]).wait();
            if (!_this.$options.justlaunch) {
                _this.$logcatHelper.start(_this.identifier);
            }
        }).future()();
    };
    AndroidApplicationManager.prototype.stopApplication = function (appIdentifier) {
        return this.adb.executeShellCommand(["am", "force-stop", ("" + appIdentifier)]);
    };
    AndroidApplicationManager.prototype.getApplicationInfo = function (applicationIdentifier) {
        return Future.fromResult(null);
    };
    AndroidApplicationManager.prototype.canStartApplication = function () {
        return true;
    };
    AndroidApplicationManager.prototype.isLiveSyncSupported = function (appIdentifier) {
        var _this = this;
        return (function () {
            var liveSyncVersion = _this.adb.sendBroadcastToDevice(constants_1.LiveSyncConstants.CHECK_LIVESYNC_INTENT_NAME, { "app-id": appIdentifier }).wait();
            return liveSyncVersion === constants_1.LiveSyncConstants.VERSION_2 || liveSyncVersion === constants_1.LiveSyncConstants.VERSION_3;
        }).future()();
    };
    AndroidApplicationManager.prototype.getDebuggableApps = function () {
        return this.$androidProcessService.getDebuggableApps(this.identifier);
    };
    AndroidApplicationManager.prototype.getDebuggableAppViews = function (appIdentifiers) {
        var _this = this;
        return (function () {
            var mappedAppIdentifierPorts = _this.$androidProcessService.getMappedAbstractToTcpPorts(_this.identifier, appIdentifiers, constants_1.TARGET_FRAMEWORK_IDENTIFIERS.Cordova).wait(), applicationViews = {};
            _.each(mappedAppIdentifierPorts, function (port, appIdentifier) {
                applicationViews[appIdentifier] = [];
                var localAddress = "http://127.0.0.1:" + port + "/json";
                try {
                    if (port) {
                        var apps = _this.$httpClient.httpRequest(localAddress).wait().body;
                        applicationViews[appIdentifier] = JSON.parse(apps);
                    }
                }
                catch (err) {
                    _this.$logger.trace("Error while checking " + localAddress + ". Error is: " + err.message);
                }
            });
            return applicationViews;
        }).future()();
    };
    __decorate([
        helpers_1.hook('install')
    ], AndroidApplicationManager.prototype, "installApplication", null);
    return AndroidApplicationManager;
}(application_manager_base_1.ApplicationManagerBase));
exports.AndroidApplicationManager = AndroidApplicationManager;
