"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const android_device_livesync_service_base_1 = require("./android-device-livesync-service-base");
const helpers = require("../../common/helpers");
const constants_1 = require("../../common/constants");
const path = require("path");
const net = require("net");
class AndroidDeviceLiveSyncService extends android_device_livesync_service_base_1.AndroidDeviceLiveSyncServiceBase {
    constructor($mobileHelper, $devicePathProvider, $injector, $androidProcessService, $platformsData, device, $filesHashService, $logger) {
        super($injector, $platformsData, $filesHashService, $logger, device);
        this.$mobileHelper = $mobileHelper;
        this.$devicePathProvider = $devicePathProvider;
        this.$androidProcessService = $androidProcessService;
        this.$platformsData = $platformsData;
        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);
        });
    }
    refreshApplication(projectData, liveSyncInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            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`]);
            const reloadedSuccessfully = yield this.reloadApplicationFiles(deviceAppData, localToDevicePaths);
            const canExecuteFastSync = reloadedSuccessfully && !liveSyncInfo.isFullSync && !_.some(localToDevicePaths, (localToDevicePath) => !this.canExecuteFastSync(liveSyncInfo, localToDevicePath.getLocalPath(), projectData, this.device.deviceInfo.platform));
            if (!canExecuteFastSync) {
                return this.restartApplication(deviceAppData, projectData.projectName);
            }
        });
    }
    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)]);
        });
    }
    restartApplication(deviceAppData, projectName) {
        return __awaiter(this, void 0, void 0, function* () {
            const devicePathRoot = `/data/data/${deviceAppData.appIdentifier}/files`;
            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: deviceAppData.appIdentifier, projectName });
        });
    }
    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);
            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]);
            }
            yield this.getDeviceHashService(deviceAppData.appIdentifier).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, '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);
                    }
                });
            });
        });
    }
}
exports.AndroidDeviceLiveSyncService = AndroidDeviceLiveSyncService;
