"use strict";
const helpers = require("../../common/helpers");
const constants = require("../../constants");
const minimatch = require("minimatch");
const net = require("net");
const Future = require("fibers/future");
let currentPageReloadId = 0;
class IOSLiveSyncService {
    constructor(_device, $iOSSocketRequestExecutor, $iOSNotification, $iOSEmulatorServices, $injector, $logger, $options, $iOSDebugService, $childProcess, $fs, $liveSyncProvider, $processService) {
        this.$iOSSocketRequestExecutor = $iOSSocketRequestExecutor;
        this.$iOSNotification = $iOSNotification;
        this.$iOSEmulatorServices = $iOSEmulatorServices;
        this.$injector = $injector;
        this.$logger = $logger;
        this.$options = $options;
        this.$iOSDebugService = $iOSDebugService;
        this.$childProcess = $childProcess;
        this.$fs = $fs;
        this.$liveSyncProvider = $liveSyncProvider;
        this.$processService = $processService;
        this.device = (_device);
    }
    get debugService() {
        return this.$iOSDebugService;
    }
    afterInstallApplicationAction(deviceAppData, localToDevicePaths) {
        return (() => {
            return this.$options.watch;
        }).future()();
    }
    setupSocketIfNeeded() {
        return (() => {
            if (this.socket) {
                return true;
            }
            if (this.device.isEmulator) {
                this.$iOSEmulatorServices.postDarwinNotification(this.$iOSNotification.attachRequest).wait();
                try {
                    this.socket = helpers.connectEventuallyUntilTimeout(() => net.connect(IOSLiveSyncService.BACKEND_PORT), 5000).wait();
                }
                catch (e) {
                    this.$logger.debug(e);
                    return false;
                }
            }
            else {
                let timeout = 9000;
                this.$iOSSocketRequestExecutor.executeAttachRequest(this.device, timeout).wait();
                this.socket = this.device.connectToPort(IOSLiveSyncService.BACKEND_PORT);
            }
            this.attachEventHandlers();
            return true;
        }).future()();
    }
    removeFiles(appIdentifier, localToDevicePaths) {
        return (() => {
            _.each(localToDevicePaths, localToDevicePathData => this.device.fileSystem.deleteFile(localToDevicePathData.getDevicePath(), appIdentifier));
        }).future()();
    }
    refreshApplication(deviceAppData, localToDevicePaths, forceExecuteFullSync) {
        return (() => {
            if (forceExecuteFullSync) {
                this.restartApplication(deviceAppData).wait();
                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(), deviceAppData.platform));
            if (shouldRestart || (!this.$options.liveEdit && scriptFiles.length)) {
                this.restartApplication(deviceAppData).wait();
                return;
            }
            if (this.setupSocketIfNeeded().wait()) {
                this.liveEdit(scriptFiles);
                this.reloadPage(deviceAppData, otherFiles).wait();
            }
            else {
                this.restartApplication(deviceAppData).wait();
            }
        }).future()();
    }
    restartApplication(deviceAppData) {
        let projectData = this.$injector.resolve("projectData");
        return this.device.applicationManager.restartApplication(deviceAppData.appIdentifier, projectData.projectName);
    }
    reloadPage(deviceAppData, localToDevicePaths) {
        return (() => {
            if (localToDevicePaths.length) {
                let message = JSON.stringify({
                    method: "Page.reload",
                    params: {
                        ignoreCache: false
                    },
                    id: ++currentPageReloadId
                });
                this.sendMessage(message).wait();
            }
        }).future()();
    }
    liveEdit(localToDevicePaths) {
        return (() => {
            _.each(localToDevicePaths, localToDevicePath => {
                let content = this.$fs.readText(localToDevicePath.getLocalPath()).wait();
                let message = JSON.stringify({
                    method: "Debugger.setScriptSource",
                    params: {
                        scriptUrl: localToDevicePath.getRelativeToProjectBasePath(),
                        scriptSource: content
                    },
                    id: ++currentPageReloadId
                });
                this.sendMessage(message).wait();
            });
        }).future()();
    }
    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 (() => {
            let socketWriteFuture = new Future();
            try {
                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 (!socketWriteFuture.isResolved()) {
                        socketWriteFuture.throw(error);
                    }
                });
                this.socket.write(payload, "utf16le", () => {
                    this.socket.removeAllListeners("error");
                    if (!socketWriteFuture.isResolved()) {
                        socketWriteFuture.return();
                    }
                });
                socketWriteFuture.wait();
            }
            catch (error) {
                this.$logger.trace("Error while sending message:", error);
                this.destroySocket();
            }
        }).future()();
    }
    destroySocket() {
        if (this.socket) {
            this.socket.destroy();
            this.socket = null;
        }
    }
}
IOSLiveSyncService.BACKEND_PORT = 18181;
$injector.register("iosLiveSyncServiceLocator", { factory: IOSLiveSyncService });
