"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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var decorators_1 = require("../../../decorators");
var ProtonLiveSyncService = (function () {
    function ProtonLiveSyncService($devicesService, $errors, $mobileHelper, $options, $fs, $injector, $project, $logger, $companionAppsService) {
        this.$devicesService = $devicesService;
        this.$errors = $errors;
        this.$mobileHelper = $mobileHelper;
        this.$options = $options;
        this.$fs = $fs;
        this.$injector = $injector;
        this.$project = $project;
        this.$logger = $logger;
        this.$companionAppsService = $companionAppsService;
        this.excludedProjectDirsAndFiles = ["app_resources", "plugins", ".*.tmp", ".ab"];
    }
    Object.defineProperty(ProtonLiveSyncService.prototype, "$liveSyncServiceBase", {
        get: function () {
            return this.$injector.resolve("liveSyncServiceBase");
        },
        enumerable: true,
        configurable: true
    });
    ProtonLiveSyncService.prototype.livesync = function (deviceDescriptors, projectDir, filePaths) {
        var _this = this;
        this.$project.projectDir = projectDir;
        this.$logger.trace("Called livesync for identifiers " + _.map(deviceDescriptors, function (d) { return d.deviceIdentifier; }) + ". Project dir is " + projectDir + ". Files are: " + filePaths);
        return _.map(deviceDescriptors, function (deviceDescriptor) { return _this.liveSyncOnDevice(deviceDescriptor, filePaths); });
    };
    ProtonLiveSyncService.prototype.deleteFiles = function (deviceDescriptors, projectDir, filePaths) {
        var _this = this;
        this.$project.projectDir = projectDir;
        this.$logger.trace("Called deleteFiles for identifiers " + _.map(deviceDescriptors, function (d) { return d.deviceIdentifier; }) + ". Project dir is " + projectDir + ". Files are: " + filePaths);
        return _.map(deviceDescriptors, function (deviceDescriptor) { return _this.liveSyncOnDevice(deviceDescriptor, filePaths, { isForDeletedFiles: true }); });
    };
    ProtonLiveSyncService.prototype.liveSyncOnDevice = function (deviceDescriptor, filePaths, liveSyncOptions) {
        var _this = this;
        return (function () {
            var isForDeletedFiles = liveSyncOptions && liveSyncOptions.isForDeletedFiles;
            _this.$devicesService.stopDeviceDetectionInterval().wait();
            var result = {
                deviceIdentifier: deviceDescriptor.deviceIdentifier
            };
            var device = _.find(_this.$devicesService.getDeviceInstances(), function (d) { return d.deviceInfo.identifier === deviceDescriptor.deviceIdentifier; });
            if (!device) {
                result.liveSyncToApp = result.liveSyncToCompanion = {
                    isResolved: false,
                    error: new Error("Cannot find connected device with identifier " + deviceDescriptor.deviceIdentifier + ". Available device identifiers are: " + _this.$devicesService.getDeviceInstances())
                };
                return result;
            }
            if (!_this.$fs.exists(_this.$project.projectDir).wait()) {
                result.liveSyncToApp = result.liveSyncToCompanion = {
                    isResolved: false,
                    error: new Error("Cannot execute LiveSync operation as the project dir " + _this.$project.projectDir + " does not exist on the file system.")
                };
                return result;
            }
            if (!isForDeletedFiles && filePaths && filePaths.length) {
                var missingFiles = filePaths.filter(function (filePath) { return !_this.$fs.exists(filePath).wait(); });
                if (missingFiles && missingFiles.length) {
                    result.liveSyncToApp = result.liveSyncToCompanion = {
                        isResolved: false,
                        error: new Error("Cannot LiveSync files " + missingFiles.join(", ") + " as they do not exist on the file system.")
                    };
                    return result;
                }
            }
            var appIdentifier = _this.$project.getAppIdentifierForPlatform(_this.$devicesService.platform).wait(), canExecute = function (d) { return d.deviceInfo.identifier === device.deviceInfo.identifier; }, livesyncData = {
                platform: device.deviceInfo.platform,
                appIdentifier: appIdentifier,
                projectFilesPath: _this.$project.projectDir,
                syncWorkingDirectory: _this.$project.projectDir,
                excludedProjectDirsAndFiles: _this.excludedProjectDirsAndFiles,
            };
            var canExecuteAction = _this.$liveSyncServiceBase.getCanExecuteAction(device.deviceInfo.platform, appIdentifier, canExecute);
            if (deviceDescriptor.syncToApp) {
                result.liveSyncToApp = _this.liveSyncCore(livesyncData, device, appIdentifier, canExecuteAction, { isForCompanionApp: false, isForDeletedFiles: isForDeletedFiles }, filePaths).wait();
            }
            if (deviceDescriptor.syncToCompanion) {
                result.liveSyncToCompanion = _this.liveSyncCore(livesyncData, device, appIdentifier, canExecuteAction, { isForCompanionApp: true, isForDeletedFiles: isForDeletedFiles }, filePaths).wait();
            }
            return result;
        }).future()();
    };
    ProtonLiveSyncService.prototype.liveSyncCore = function (livesyncData, device, appIdentifier, canExecuteAction, liveSyncOptions, filePaths) {
        var _this = this;
        return (function () {
            var liveSyncOperationResult = {
                isResolved: false
            };
            if (liveSyncOptions.isForCompanionApp) {
                livesyncData.appIdentifier = appIdentifier = _this.$companionAppsService.getCompanionAppIdentifier(_this.$project.projectData.Framework, device.deviceInfo.platform);
            }
            if (device.applicationManager.isApplicationInstalled(appIdentifier).wait()) {
                var deletedFilesAction = liveSyncOptions && liveSyncOptions.isForDeletedFiles ? _this.$liveSyncServiceBase.getSyncRemovedFilesAction(livesyncData) : null;
                var action = _this.$liveSyncServiceBase.getSyncAction(livesyncData, filePaths, deletedFilesAction, liveSyncOptions);
                try {
                    _this.$devicesService.execute(action, canExecuteAction).wait();
                    liveSyncOperationResult.isResolved = true;
                }
                catch (err) {
                    liveSyncOperationResult.error = err;
                    liveSyncOperationResult.isResolved = false;
                }
            }
            else {
                liveSyncOperationResult.error = new Error("Application with id " + appIdentifier + " is not installed on device with id " + device.deviceInfo.identifier + " and it cannot be livesynced.");
                liveSyncOperationResult.isResolved = false;
            }
            return liveSyncOperationResult;
        }).future()();
    };
    __decorate([
        decorators_1.exportedPromise("liveSyncService", function () {
            this.$devicesService.startDeviceDetectionInterval();
        }), 
        __metadata('design:type', Function), 
        __metadata('design:paramtypes', [Array, String, Array]), 
        __metadata('design:returntype', Array)
    ], ProtonLiveSyncService.prototype, "livesync", null);
    __decorate([
        decorators_1.exportedPromise("liveSyncService"), 
        __metadata('design:type', Function), 
        __metadata('design:paramtypes', [Array, String, Array]), 
        __metadata('design:returntype', Array)
    ], ProtonLiveSyncService.prototype, "deleteFiles", null);
    return ProtonLiveSyncService;
}());
exports.ProtonLiveSyncService = ProtonLiveSyncService;
$injector.register("liveSyncService", ProtonLiveSyncService);
