"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 helpers = require("../../common/helpers");
const constants = require("../../constants");
const minimatch = require("minimatch");
const net = require("net");
let currentPageReloadId = 0;
class IOSLiveSyncService {
    constructor(_device, $iOSSocketRequestExecutor, $iOSNotification, $iOSEmulatorServices, $logger, $options, $iOSDebugService, $fs, $liveSyncProvider, $processService) {
        this.$iOSSocketRequestExecutor = $iOSSocketRequestExecutor;
        this.$iOSNotification = $iOSNotification;
        this.$iOSEmulatorServices = $iOSEmulatorServices;
        this.$logger = $logger;
        this.$options = $options;
        this.$iOSDebugService = $iOSDebugService;
        this.$fs = $fs;
        this.$liveSyncProvider = $liveSyncProvider;
        this.$processService = $processService;
        this.device = _device;
    }
    get debugService() {
        return this.$iOSDebugService;
    }
    afterInstallApplicationAction(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.$options.watch;
        });
    }
    setupSocketIfNeeded(projectId) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.socket) {
                return true;
            }
            if (this.device.isEmulator) {
                yield this.$iOSEmulatorServices.postDarwinNotification(this.$iOSNotification.getAttachRequest(projectId));
                try {
                    this.socket = yield helpers.connectEventuallyUntilTimeout(() => net.connect(IOSLiveSyncService.BACKEND_PORT), 5000);
                }
                catch (e) {
                    this.$logger.debug(e);
                    return false;
                }
            }
            else {
                let timeout = 9000;
                yield this.$iOSSocketRequestExecutor.executeAttachRequest(this.device, timeout, projectId);
                this.socket = yield this.device.connectToPort(IOSLiveSyncService.BACKEND_PORT);
            }
            this.attachEventHandlers();
            return true;
        });
    }
    removeFiles(appIdentifier, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            yield Promise.all(_.map(localToDevicePaths, localToDevicePathData => this.device.fileSystem.deleteFile(localToDevicePathData.getDevicePath(), appIdentifier)));
        });
    }
    refreshApplication(deviceAppData, localToDevicePaths, forceExecuteFullSync, projectData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (forceExecuteFullSync) {
                yield this.restartApplication(deviceAppData);
                return;
            }
            let scriptRelatedFiles = [];
            let scriptFiles = _.filter(localToDevicePaths, localToDevicePath => _.endsWith(localToDevicePath.getDevicePath(), ".js"));
            constants.LIVESYNC_EXCLUDED_FILE_PATTERNS.forEach(pattern => scriptRelatedFiles = _.concat(scriptRelatedFiles, localToDevicePaths.filter(file => minimatch(file.getDevicePath(), pattern, { nocase: true }))));
            let otherFiles = _.difference(localToDevicePaths, _.concat(scriptFiles, scriptRelatedFiles));
            let shouldRestart = _.some(otherFiles, (localToDevicePath) => !this.$liveSyncProvider.canExecuteFastSync(localToDevicePath.getLocalPath(), projectData, deviceAppData.platform));
            if (shouldRestart || (!this.$options.liveEdit && scriptFiles.length)) {
                yield this.restartApplication(deviceAppData);
                return;
            }
            if (yield this.setupSocketIfNeeded(projectData.projectId)) {
                this.liveEdit(scriptFiles);
                yield this.reloadPage(deviceAppData, otherFiles);
            }
            else {
                yield this.restartApplication(deviceAppData);
            }
        });
    }
    restartApplication(deviceAppData) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.device.applicationManager.restartApplication(deviceAppData.appIdentifier);
        });
    }
    reloadPage(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            if (localToDevicePaths.length) {
                let message = JSON.stringify({
                    method: "Page.reload",
                    params: {
                        ignoreCache: false
                    },
                    id: ++currentPageReloadId
                });
                yield this.sendMessage(message);
            }
        });
    }
    liveEdit(localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            for (let localToDevicePath of localToDevicePaths) {
                let content = this.$fs.readText(localToDevicePath.getLocalPath());
                let message = JSON.stringify({
                    method: "Debugger.setScriptSource",
                    params: {
                        scriptUrl: localToDevicePath.getRelativeToProjectBasePath(),
                        scriptSource: content
                    },
                    id: ++currentPageReloadId
                });
                yield this.sendMessage(message);
            }
        });
    }
    attachEventHandlers() {
        this.$processService.attachToProcessExitSignals(this, this.destroySocket);
        this.socket.on("close", (hadError) => {
            this.$logger.trace(`Socket closed, hadError is ${hadError}.`);
            this.socket = null;
        });
        this.socket.on("error", (error) => {
            this.$logger.trace(`Socket error received: ${error}`);
        });
        this.socket.on("data", (data) => {
            this.$logger.trace(`Socket sent data: ${data.toString()}`);
        });
    }
    sendMessage(message) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                yield new Promise((resolve, reject) => {
                    let isResolved = false;
                    let length = Buffer.byteLength(message, "utf16le");
                    let payload = new Buffer(length + 4);
                    payload.writeInt32BE(length, 0);
                    payload.write(message, 4, length, "utf16le");
                    this.socket.once("error", (error) => {
                        if (!isResolved) {
                            isResolved = true;
                            reject(error);
                        }
                    });
                    this.socket.write(payload, "utf16le", () => {
                        this.socket.removeAllListeners("error");
                        if (!isResolved) {
                            isResolved = true;
                            resolve();
                        }
                    });
                });
            }
            catch (error) {
                this.$logger.trace("Error while sending message:", error);
                this.destroySocket();
            }
        });
    }
    destroySocket() {
        if (this.socket) {
            this.socket.destroy();
            this.socket = null;
        }
    }
}
IOSLiveSyncService.BACKEND_PORT = 18181;
$injector.register("iosLiveSyncServiceLocator", { factory: IOSLiveSyncService });
