"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AndroidDeviceLiveSyncService = void 0;
const android_device_livesync_service_base_1 = require("./android-device-livesync-service-base");
const decorators_1 = require("../../common/decorators");
const helpers = require("../../common/helpers");
const constants_1 = require("../../common/constants");
const constants_2 = require("../../constants");
const util = require("util");
const path = require("path");
const net = require("net");
const _ = require("lodash");
class AndroidDeviceLiveSyncService extends android_device_livesync_service_base_1.AndroidDeviceLiveSyncServiceBase {
    constructor($mobileHelper, $devicePathProvider, $injector, $androidProcessService, platformsDataService, device, $filesHashService, $logger) {
        super($injector, platformsDataService, $filesHashService, $logger, device);
        this.$mobileHelper = $mobileHelper;
        this.$devicePathProvider = $devicePathProvider;
        this.$androidProcessService = $androidProcessService;
        this.platformsDataService = platformsDataService;
        this.device = device;
    }
    transferFilesOnDevice(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.device.fileSystem.transferFiles(deviceAppData, localToDevicePaths);
        });
    }
    transferDirectoryOnDevice(deviceAppData, localToDevicePaths, projectFilesPath) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.device.fileSystem.transferDirectory(deviceAppData, localToDevicePaths, projectFilesPath);
        });
    }
    restartApplication(projectData, liveSyncInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            const devicePathRoot = util.format(constants_2.ANDROID_DEVICE_APP_ROOT_TEMPLATE, liveSyncInfo.deviceAppData.appIdentifier);
            const devicePath = this.$mobileHelper.buildDevicePath(devicePathRoot, "code_cache", "secondary_dexes", "proxyThumb");
            yield this.device.adb.executeShellCommand(["rm", "-rf", devicePath]);
            yield this.device.applicationManager.restartApplication({
                appId: liveSyncInfo.deviceAppData.appIdentifier,
                projectName: projectData.projectName,
                waitForDebugger: liveSyncInfo.waitForDebugger,
                projectDir: projectData.projectDir,
            });
        });
    }
    shouldRestart(projectData, liveSyncInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            let shouldRestart = false;
            const localToDevicePaths = liveSyncInfo.modifiedFilesData;
            const canExecuteFastSync = !liveSyncInfo.isFullSync &&
                !_.some(localToDevicePaths, (localToDevicePath) => !this.canExecuteFastSync(liveSyncInfo, localToDevicePath.getLocalPath(), projectData, this.device.deviceInfo.platform));
            if (!canExecuteFastSync || liveSyncInfo.waitForDebugger) {
                shouldRestart = true;
            }
            return shouldRestart;
        });
    }
    tryRefreshApplication(projectData, liveSyncInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            let didRefresh = true;
            const deviceAppData = liveSyncInfo.deviceAppData;
            const localToDevicePaths = liveSyncInfo.modifiedFilesData;
            const deviceProjectRootDirname = yield this.$devicePathProvider.getDeviceProjectRootPath(liveSyncInfo.deviceAppData.device, {
                appIdentifier: liveSyncInfo.deviceAppData.appIdentifier,
                getDirname: true,
            });
            yield this.device.adb.executeShellCommand([
                "chmod",
                "777",
                path.dirname(deviceProjectRootDirname),
                deviceProjectRootDirname,
                `${deviceProjectRootDirname}/sync`,
            ]);
            didRefresh = yield this.reloadApplicationFiles(deviceAppData, localToDevicePaths);
            return didRefresh;
        });
    }
    cleanLivesyncDirectories(deviceAppData) {
        return __awaiter(this, void 0, void 0, function* () {
            const deviceRootPath = yield this.$devicePathProvider.getDeviceProjectRootPath(deviceAppData.device, {
                appIdentifier: deviceAppData.appIdentifier,
                getDirname: true,
            });
            yield this.device.adb.executeShellCommand([
                "rm",
                "-rf",
                this.$mobileHelper.buildDevicePath(deviceRootPath, constants_1.LiveSyncPaths.FULLSYNC_DIR_NAME),
                this.$mobileHelper.buildDevicePath(deviceRootPath, constants_1.LiveSyncPaths.SYNC_DIR_NAME),
                this.$mobileHelper.buildDevicePath(deviceRootPath, constants_1.LiveSyncPaths.REMOVEDSYNC_DIR_NAME),
            ]);
        });
    }
    beforeLiveSyncAction(deviceAppData) {
        return __awaiter(this, void 0, void 0, function* () {
            const deviceRootPath = yield this.$devicePathProvider.getDeviceProjectRootPath(deviceAppData.device, {
                appIdentifier: deviceAppData.appIdentifier,
                getDirname: true,
            });
            const deviceRootDir = path.dirname(deviceRootPath);
            const deviceRootBasename = path.basename(deviceRootPath);
            const listResult = yield this.device.adb.executeShellCommand([
                "ls",
                "-l",
                deviceRootDir,
            ]);
            const regex = new RegExp(`^-.*${deviceRootBasename}$`, "m");
            const matchingFile = (listResult || "").match(regex);
            // Check if there is already a file with deviceRootBasename. If so, delete it as it breaks LiveSyncing.
            if (matchingFile && matchingFile[0] && _.startsWith(matchingFile[0], "-")) {
                yield this.device.adb.executeShellCommand(["rm", "-f", deviceRootPath]);
            }
            yield this.cleanLivesyncDirectories(deviceAppData);
        });
    }
    reloadApplicationFiles(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.port) {
                this.port = yield this.$androidProcessService.forwardFreeTcpToAbstractPort({
                    deviceIdentifier: deviceAppData.device.deviceInfo.identifier,
                    appIdentifier: deviceAppData.appIdentifier,
                    abstractPort: `localabstract:${deviceAppData.appIdentifier}-livesync`,
                });
            }
            if (yield this.awaitRuntimeReloadSuccessMessage()) {
                yield this.cleanLivesyncDirectories(deviceAppData);
            }
            else {
                return false;
            }
            return true;
        });
    }
    removeFiles(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            const deviceRootPath = yield this.$devicePathProvider.getDeviceProjectRootPath(deviceAppData.device, {
                appIdentifier: deviceAppData.appIdentifier,
                getDirname: true,
            });
            for (const localToDevicePathData of localToDevicePaths) {
                const relativeUnixPath = _.trimStart(helpers.fromWindowsRelativePathToUnix(localToDevicePathData.getRelativeToProjectBasePath()), "/");
                const deviceFilePath = this.$mobileHelper.buildDevicePath(deviceRootPath, constants_1.LiveSyncPaths.REMOVEDSYNC_DIR_NAME, relativeUnixPath);
                yield this.device.adb.executeShellCommand([
                    "mkdir",
                    "-p",
                    path.dirname(deviceFilePath),
                    " && ",
                    "touch",
                    deviceFilePath,
                ]);
            }
            const deviceHashService = this.device.fileSystem.getDeviceHashService(deviceAppData.appIdentifier);
            yield deviceHashService.removeHashes(localToDevicePaths);
        });
    }
    awaitRuntimeReloadSuccessMessage() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                let isResolved = false;
                const socket = new net.Socket();
                socket.connect(this.port, process.env.NATIVESCRIPT_LIVESYNC_ADDRESS || "127.0.0.1", () => {
                    socket.write(Buffer.from([0, 0, 0, 1, 1]));
                });
                socket.on("data", (data) => {
                    isResolved = true;
                    socket.destroy();
                    resolve(true);
                });
                socket.on("error", () => {
                    if (!isResolved) {
                        isResolved = true;
                        resolve(false);
                    }
                });
                socket.on("close", () => {
                    if (!isResolved) {
                        isResolved = true;
                        resolve(false);
                    }
                });
            });
        });
    }
}
__decorate([
    (0, decorators_1.performanceLog)()
], AndroidDeviceLiveSyncService.prototype, "beforeLiveSyncAction", null);
__decorate([
    (0, decorators_1.performanceLog)()
], AndroidDeviceLiveSyncService.prototype, "removeFiles", null);
exports.AndroidDeviceLiveSyncService = AndroidDeviceLiveSyncService;
//# sourceMappingURL=android-device-livesync-service.js.map