"use strict";
var path = require("path");
var temp = require("temp");
var android_device_hash_service_1 = require("./android-device-hash-service");
var Future = require("fibers/future");
var AndroidDeviceFileSystem = (function () {
    function AndroidDeviceFileSystem(adb, identifier, $fs, $logger, $mobileHelper, $injector, $options) {
        this.adb = adb;
        this.identifier = identifier;
        this.$fs = $fs;
        this.$logger = $logger;
        this.$mobileHelper = $mobileHelper;
        this.$injector = $injector;
        this.$options = $options;
        this._deviceHashServices = Object.create(null);
    }
    AndroidDeviceFileSystem.prototype.listFiles = function (devicePath) {
        return Future.fromResult();
    };
    AndroidDeviceFileSystem.prototype.getFile = function (deviceFilePath) {
        return Future.fromResult();
    };
    AndroidDeviceFileSystem.prototype.putFile = function (localFilePath, deviceFilePath) {
        return Future.fromResult();
    };
    AndroidDeviceFileSystem.prototype.transferFiles = function (deviceAppData, localToDevicePaths) {
        var _this = this;
        return (function () {
            _(localToDevicePaths)
                .filter(function (localToDevicePathData) { return _this.$fs.getFsStats(localToDevicePathData.getLocalPath()).wait().isFile(); })
                .each(function (localToDevicePathData) {
                return _this.adb.executeCommand(["push", localToDevicePathData.getLocalPath(), localToDevicePathData.getDevicePath()]).wait();
            })
                .value();
            _(localToDevicePaths)
                .filter(function (localToDevicePathData) { return _this.$fs.getFsStats(localToDevicePathData.getLocalPath()).wait().isDirectory(); })
                .each(function (localToDevicePathData) {
                return _this.adb.executeShellCommand(["chmod", "0777", localToDevicePathData.getDevicePath()]).wait();
            })
                .value();
            var deviceHashService = _this.getDeviceHashService(deviceAppData.appIdentifier);
            if (!deviceHashService.updateHashes(localToDevicePaths).wait()) {
                _this.$logger.trace("Unable to find hash file on device. The next livesync command will create it.");
            }
        }).future()();
    };
    AndroidDeviceFileSystem.prototype.transferDirectory = function (deviceAppData, localToDevicePaths, projectFilesPath) {
        var _this = this;
        return (function () {
            var devicePaths = [], currentShasums = {};
            localToDevicePaths.forEach(function (localToDevicePathData) {
                var localPath = localToDevicePathData.getLocalPath();
                var stats = _this.$fs.getFsStats(localPath).wait();
                if (stats.isFile()) {
                    var fileShasum = _this.$fs.getFileShasum(localPath).wait();
                    currentShasums[localPath] = fileShasum;
                }
                devicePaths.push("\"" + localToDevicePathData.getDevicePath() + "\"");
            });
            var commandsDeviceFilePath = _this.$mobileHelper.buildDevicePath(deviceAppData.deviceProjectRootPath, "nativescript.commands.sh");
            var deviceHashService = _this.getDeviceHashService(deviceAppData.appIdentifier);
            var filesToChmodOnDevice = devicePaths;
            if (_this.$options.force) {
                _this.adb.executeShellCommand(["rm", "-rf", deviceHashService.hashFileDevicePath]).wait();
                _this.adb.executeCommand(["push", projectFilesPath, deviceAppData.deviceProjectRootPath]).wait();
            }
            else {
                var oldShasums = deviceHashService.getShasumsFromDevice().wait();
                if (oldShasums) {
                    var changedShasums = _.omit(currentShasums, function (hash, pathToFile) { return !!_.find(oldShasums, function (oldHash, oldPath) { return pathToFile === oldPath && hash === oldHash; }); });
                    _this.$logger.trace("Changed file hashes are:", changedShasums);
                    filesToChmodOnDevice = [];
                    var futures = _(changedShasums)
                        .map(function (hash, filePath) { return _.find(localToDevicePaths, function (ldp) { return ldp.getLocalPath() === filePath; }); })
                        .map(function (localToDevicePathData) {
                        filesToChmodOnDevice.push("\"" + localToDevicePathData.getDevicePath() + "\"");
                        return _this.transferFile(localToDevicePathData.getLocalPath(), localToDevicePathData.getDevicePath());
                    })
                        .value();
                    Future.wait(futures);
                }
                else {
                    _this.adb.executeCommand(["push", projectFilesPath, deviceAppData.deviceProjectRootPath]).wait();
                }
            }
            if (filesToChmodOnDevice.length) {
                _this.createFileOnDevice(commandsDeviceFilePath, "chmod 0777 " + filesToChmodOnDevice.join(" ")).wait();
                _this.adb.executeShellCommand([commandsDeviceFilePath]).wait();
            }
            deviceHashService.uploadHashFileToDevice(currentShasums).wait();
        }).future()();
    };
    AndroidDeviceFileSystem.prototype.transferFile = function (localPath, devicePath) {
        var _this = this;
        return (function () {
            _this.$logger.trace("Transfering " + localPath + " to " + devicePath);
            var stats = _this.$fs.getFsStats(localPath).wait();
            if (stats.isDirectory()) {
                _this.adb.executeShellCommand(["mkdir", path.dirname(devicePath)]).wait();
            }
            else {
                _this.adb.executeCommand(["push", localPath, devicePath]).wait();
            }
        }).future()();
    };
    AndroidDeviceFileSystem.prototype.createFileOnDevice = function (deviceFilePath, fileContent) {
        var _this = this;
        return (function () {
            var hostTmpDir = _this.getTempDir();
            var commandsFileHostPath = path.join(hostTmpDir, "temp.commands.file");
            _this.$fs.writeFile(commandsFileHostPath, fileContent).wait();
            _this.transferFile(commandsFileHostPath, deviceFilePath).wait();
            _this.adb.executeShellCommand(["chmod", "0777", deviceFilePath]).wait();
        }).future()();
    };
    AndroidDeviceFileSystem.prototype.getTempDir = function () {
        temp.track();
        return temp.mkdirSync("application-");
    };
    AndroidDeviceFileSystem.prototype.getDeviceHashService = function (appIdentifier) {
        if (!this._deviceHashServices[appIdentifier]) {
            this._deviceHashServices[appIdentifier] = this.$injector.resolve(android_device_hash_service_1.AndroidDeviceHashService, { adb: this.adb, appIdentifier: appIdentifier });
        }
        return this._deviceHashServices[appIdentifier];
    };
    return AndroidDeviceFileSystem;
})();
exports.AndroidDeviceFileSystem = AndroidDeviceFileSystem;
