"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());
    });
};
const device_android_debug_bridge_1 = require("../../common/mobile/android/device-android-debug-bridge");
const android_device_hash_service_1 = require("../../common/mobile/android/android-device-hash-service");
const helpers = require("../../common/helpers");
const path = require("path");
const net = require("net");
class AndroidLiveSyncService {
    constructor(_device, $mobileHelper, $injector, $projectData, $androidDebugService, $liveSyncProvider) {
        this.$mobileHelper = $mobileHelper;
        this.$injector = $injector;
        this.$projectData = $projectData;
        this.$androidDebugService = $androidDebugService;
        this.$liveSyncProvider = $liveSyncProvider;
        this.device = (_device);
    }
    get debugService() {
        return this.$androidDebugService;
    }
    refreshApplication(deviceAppData, localToDevicePaths, forceExecuteFullSync) {
        return __awaiter(this, void 0, void 0, function* () {
            let canExecuteFastSync = !forceExecuteFullSync && !_.some(localToDevicePaths, (localToDevicePath) => !this.$liveSyncProvider.canExecuteFastSync(localToDevicePath.getLocalPath(), deviceAppData.platform));
            if (canExecuteFastSync) {
                return this.reloadPage(deviceAppData, localToDevicePaths);
            }
            return this.restartApplication(deviceAppData);
        });
    }
    restartApplication(deviceAppData) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.device.adb.executeShellCommand(["chmod", "777", yield deviceAppData.getDeviceProjectRootPath(), `/data/local/tmp/${deviceAppData.appIdentifier}`]);
            let devicePathRoot = `/data/data/${deviceAppData.appIdentifier}/files`;
            let devicePath = this.$mobileHelper.buildDevicePath(devicePathRoot, "code_cache", "secondary_dexes", "proxyThumb");
            yield this.device.adb.executeShellCommand(["rm", "-rf", devicePath]);
            yield this.device.applicationManager.restartApplication(deviceAppData.appIdentifier);
        });
    }
    beforeLiveSyncAction(deviceAppData) {
        return __awaiter(this, void 0, void 0, function* () {
            let deviceRootPath = this.getDeviceRootPath(deviceAppData.appIdentifier), deviceRootDir = path.dirname(deviceRootPath), deviceRootBasename = path.basename(deviceRootPath), listResult = yield this.device.adb.executeShellCommand(["ls", "-l", deviceRootDir]), regex = new RegExp(`^-.*${deviceRootBasename}$`, "m"), matchingFile = (listResult || "").match(regex);
            if (matchingFile && matchingFile[0] && _.startsWith(matchingFile[0], '-')) {
                yield this.device.adb.executeShellCommand(["rm", "-f", deviceRootPath]);
            }
            this.device.adb.executeShellCommand(["rm", "-rf", this.$mobileHelper.buildDevicePath(deviceRootPath, "fullsync"),
                this.$mobileHelper.buildDevicePath(deviceRootPath, "sync"),
                yield this.$mobileHelper.buildDevicePath(deviceRootPath, "removedsync")]);
        });
    }
    reloadPage(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.device.adb.executeCommand(["forward", `tcp:${AndroidLiveSyncService.BACKEND_PORT.toString()}`, `localabstract:${deviceAppData.appIdentifier}-livesync`]);
            if (!(yield this.sendPageReloadMessage())) {
                yield this.restartApplication(deviceAppData);
            }
        });
    }
    removeFiles(appIdentifier, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            let deviceRootPath = this.getDeviceRootPath(appIdentifier);
            _.each(localToDevicePaths, localToDevicePathData => {
                let relativeUnixPath = _.trimStart(helpers.fromWindowsRelativePathToUnix(localToDevicePathData.getRelativeToProjectBasePath()), "/");
                let deviceFilePath = this.$mobileHelper.buildDevicePath(deviceRootPath, "removedsync", relativeUnixPath);
                this.device.adb.executeShellCommand(["mkdir", "-p", path.dirname(deviceFilePath), "&& await ", "touch", deviceFilePath]);
            });
            yield this.deviceHashService.removeHashes(localToDevicePaths);
        });
    }
    afterInstallApplicationAction(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.deviceHashService.uploadHashFileToDevice(localToDevicePaths);
            return false;
        });
    }
    getDeviceRootPath(appIdentifier) {
        return `/data/local/tmp/${appIdentifier}`;
    }
    sendPageReloadMessage() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                let isResolved = false;
                let socket = new net.Socket();
                socket.connect(AndroidLiveSyncService.BACKEND_PORT, '127.0.0.1', () => {
                    socket.write(new Buffer([0, 0, 0, 1, 1]));
                });
                socket.on("data", (data) => {
                    socket.destroy();
                    resolve(true);
                });
                socket.on("error", () => {
                    if (!isResolved) {
                        isResolved = true;
                        resolve(false);
                    }
                });
                socket.on("close", () => {
                    if (!isResolved) {
                        isResolved = true;
                        resolve(false);
                    }
                });
            });
        });
    }
    get deviceHashService() {
        if (!this._deviceHashService) {
            let adb = this.$injector.resolve(device_android_debug_bridge_1.DeviceAndroidDebugBridge, { identifier: this.device.deviceInfo.identifier });
            this._deviceHashService = this.$injector.resolve(android_device_hash_service_1.AndroidDeviceHashService, { adb: adb, appIdentifier: this.$projectData.projectId });
        }
        return this._deviceHashService;
    }
}
AndroidLiveSyncService.BACKEND_PORT = 18182;
$injector.register("androidLiveSyncServiceLocator", { factory: AndroidLiveSyncService });
