"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) {
    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 constants = require("../../constants");
const minimatch = require("minimatch");
const device_livesync_service_base_1 = require("./device-livesync-service-base");
const decorators_1 = require("../../common/decorators");
let currentPageReloadId = 0;
class IOSDeviceLiveSyncService extends device_livesync_service_base_1.DeviceLiveSyncServiceBase {
    constructor($logger, platformsDataService, device) {
        super(platformsDataService, device);
        this.$logger = $logger;
        this.platformsDataService = platformsDataService;
        this.device = device;
    }
    setupSocketIfNeeded(projectData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.socket) {
                return true;
            }
            const appId = projectData.projectIdentifiers.ios;
            try {
                const ensureAppStarted = true;
                this.socket = yield this.device.getDebugSocket(appId, projectData.projectName, projectData.projectDir, ensureAppStarted);
            }
            catch (err) {
                this.$logger.trace(`Error while connecting to the debug socket. Error is:`, err);
            }
            if (!this.socket) {
                return false;
            }
            this.attachEventHandlers();
            return true;
        });
    }
    removeFiles(deviceAppData, localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            yield Promise.all(_.map(localToDevicePaths, localToDevicePathData => this.device.fileSystem.deleteFile(localToDevicePathData.getDevicePath(), deviceAppData.appIdentifier)));
        });
    }
    shouldRestart(projectData, liveSyncInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            let shouldRestart = false;
            const deviceAppData = liveSyncInfo.deviceAppData;
            const localToDevicePaths = liveSyncInfo.modifiedFilesData;
            if (liveSyncInfo.isFullSync || liveSyncInfo.waitForDebugger) {
                shouldRestart = true;
            }
            else {
                const canExecuteFastSync = this.canExecuteFastSyncForPaths(liveSyncInfo, localToDevicePaths, projectData, deviceAppData.platform);
                if (!canExecuteFastSync || !(yield this.setupSocketIfNeeded(projectData))) {
                    shouldRestart = true;
                }
            }
            return shouldRestart;
        });
    }
    tryRefreshApplication(projectData, liveSyncInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            let didRefresh = true;
            const localToDevicePaths = liveSyncInfo.modifiedFilesData;
            let scriptRelatedFiles = [];
            constants.LIVESYNC_EXCLUDED_FILE_PATTERNS.forEach(pattern => scriptRelatedFiles = _.concat(scriptRelatedFiles, localToDevicePaths.filter(file => minimatch(file.getDevicePath(), pattern, { nocase: true }))));
            const scriptFiles = _.filter(localToDevicePaths, localToDevicePath => _.endsWith(localToDevicePath.getDevicePath(), ".js"));
            const otherFiles = _.difference(localToDevicePaths, _.concat(scriptFiles, scriptRelatedFiles));
            try {
                if (yield this.setupSocketIfNeeded(projectData)) {
                    yield this.reloadPage(otherFiles);
                }
                else {
                    didRefresh = false;
                }
            }
            catch (e) {
                didRefresh = false;
            }
            return didRefresh;
        });
    }
    restartApplication(projectData, liveSyncInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.device.applicationManager.restartApplication({
                appId: liveSyncInfo.deviceAppData.appIdentifier,
                projectName: projectData.projectName,
                waitForDebugger: liveSyncInfo.waitForDebugger,
                projectDir: projectData.projectDir
            });
        });
    }
    reloadPage(localToDevicePaths) {
        return __awaiter(this, void 0, void 0, function* () {
            if (localToDevicePaths.length) {
                const message = JSON.stringify({
                    method: "Page.reload",
                    params: {
                        ignoreCache: false
                    },
                    id: ++currentPageReloadId
                });
                yield this.sendMessage(message);
            }
        });
    }
    attachEventHandlers() {
        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;
                    const length = Buffer.byteLength(message, "utf16le");
                    const payload = Buffer.allocUnsafe(length + 4);
                    payload.writeInt32BE(length, 0);
                    payload.write(message, 4, length, "utf16le");
                    const errorCallback = (error) => {
                        if (!isResolved) {
                            isResolved = true;
                            reject(error);
                        }
                    };
                    this.socket.once("error", errorCallback);
                    this.socket.write(payload, "utf16le", () => {
                        this.socket.removeListener("error", errorCallback);
                        if (!isResolved) {
                            isResolved = true;
                            resolve();
                        }
                    });
                });
            }
            catch (error) {
                this.$logger.trace("Error while sending message:", error);
                yield this.destroySocket();
            }
        });
    }
    destroySocket() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.socket) {
                yield this.device.destroyAllSockets();
                this.socket = null;
            }
        });
    }
}
__decorate([
    decorators_1.performanceLog()
], IOSDeviceLiveSyncService.prototype, "removeFiles", null);
exports.IOSDeviceLiveSyncService = IOSDeviceLiveSyncService;
