"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());
    });
};
const constants = require("../../constants");
const helpers = require("../../common/helpers");
const path = require("path");
const semver = require("semver");
const node_modules_dependencies_builder_1 = require("../../tools/node-modules/node-modules-dependencies-builder");
let choki = require("chokidar");
class LiveSyncService {
    constructor($devicePlatformsConstants, $errors, $platformsData, $platformService, $projectData, $projectDataService, $prompter, $injector, $mobileHelper, $devicesService, $options, $logger, $dispatcher, $hooksService, $processService) {
        this.$devicePlatformsConstants = $devicePlatformsConstants;
        this.$errors = $errors;
        this.$platformsData = $platformsData;
        this.$platformService = $platformService;
        this.$projectData = $projectData;
        this.$projectDataService = $projectDataService;
        this.$prompter = $prompter;
        this.$injector = $injector;
        this.$mobileHelper = $mobileHelper;
        this.$devicesService = $devicesService;
        this.$options = $options;
        this.$logger = $logger;
        this.$dispatcher = $dispatcher;
        this.$hooksService = $hooksService;
        this.$processService = $processService;
        this._isInitialized = false;
    }
    ensureAndroidFrameworkVersion(platformData) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$projectDataService.initialize(this.$projectData.projectDir);
            let frameworkVersion = this.$projectDataService.getValue(platformData.frameworkPackageName).version;
            if (platformData.normalizedPlatformName.toLowerCase() === this.$devicePlatformsConstants.Android.toLowerCase()) {
                if (semver.lt(frameworkVersion, "1.2.1")) {
                    let shouldUpdate = yield this.$prompter.confirm("You need Android Runtime 1.2.1 or later for LiveSync to work properly. Do you want to update your runtime now?");
                    if (shouldUpdate) {
                        yield this.$platformService.updatePlatforms([this.$devicePlatformsConstants.Android.toLowerCase()]);
                    }
                    else {
                        return;
                    }
                }
            }
        });
    }
    get isInitialized() {
        return this._isInitialized;
    }
    liveSync(platform, applicationReloadAction) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.$options.justlaunch) {
                this.$options.watch = false;
            }
            let liveSyncData = [];
            if (platform) {
                yield this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device });
                liveSyncData.push(yield this.prepareLiveSyncData(platform));
            }
            else if (this.$options.device) {
                yield this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device });
                platform = this.$devicesService.getDeviceByIdentifier(this.$options.device).deviceInfo.platform;
                liveSyncData.push(yield this.prepareLiveSyncData(platform));
            }
            else {
                yield this.$devicesService.initialize({ skipInferPlatform: true });
                yield this.$devicesService.stopDeviceDetectionInterval();
                for (let installedPlatform of this.$platformService.getInstalledPlatforms()) {
                    if (this.$devicesService.getDevicesForPlatform(installedPlatform).length === 0) {
                        yield this.$devicesService.startEmulator(installedPlatform);
                    }
                    liveSyncData.push(yield this.prepareLiveSyncData(installedPlatform));
                }
            }
            if (liveSyncData.length === 0) {
                this.$errors.fail("There are no platforms installed in this project. Please specify platform or install one by using `tns platform add` command!");
            }
            this._isInitialized = true;
            yield this.liveSyncCore(liveSyncData, applicationReloadAction);
        });
    }
    prepareLiveSyncData(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            platform = platform || this.$devicesService.platform;
            let platformData = this.$platformsData.getPlatformData(platform.toLowerCase());
            if (this.$mobileHelper.isAndroidPlatform(platform)) {
                yield this.ensureAndroidFrameworkVersion(platformData);
            }
            let liveSyncData = {
                platform: platform,
                appIdentifier: this.$projectData.projectId,
                projectFilesPath: path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME),
                syncWorkingDirectory: this.$projectData.projectDir,
                excludedProjectDirsAndFiles: this.$options.release ? constants.LIVESYNC_EXCLUDED_FILE_PATTERNS : []
            };
            return liveSyncData;
        });
    }
    liveSyncCore(liveSyncData, applicationReloadAction) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.$platformService.trackProjectType();
            let watchForChangeActions = [];
            for (let dataItem of liveSyncData) {
                let service = this.$injector.resolve("platformLiveSyncService", { _liveSyncData: dataItem });
                watchForChangeActions.push((event, filePath, dispatcher) => service.partialSync(event, filePath, dispatcher, applicationReloadAction));
                yield service.fullSync(applicationReloadAction);
            }
            if (this.$options.watch && !this.$options.justlaunch) {
                yield this.$hooksService.executeBeforeHooks('watch');
                yield this.partialSync(liveSyncData[0].syncWorkingDirectory, watchForChangeActions);
            }
        });
    }
    partialSync(syncWorkingDirectory, onChangedActions) {
        let that = this;
        let dependenciesBuilder = this.$injector.resolve(node_modules_dependencies_builder_1.NodeModulesDependenciesBuilder, {});
        let productionDependencies = dependenciesBuilder.getProductionDependencies(this.$projectData.projectDir);
        let pattern = ["app"];
        if (this.$options.syncAllFiles) {
            pattern.push("package.json");
            for (let index in productionDependencies) {
                pattern.push("node_modules/" + productionDependencies[index].name);
            }
        }
        let watcher = choki.watch(pattern, { ignoreInitial: true, cwd: syncWorkingDirectory, ignored: '**/*.DS_Store' }).on("all", (event, filePath) => {
            that.$dispatcher.dispatch(() => __awaiter(this, void 0, void 0, function* () {
                try {
                    filePath = path.join(syncWorkingDirectory, filePath);
                    for (let i = 0; i < onChangedActions.length; i++) {
                        yield onChangedActions[i](event, filePath, that.$dispatcher);
                    }
                }
                catch (err) {
                    that.$logger.info(`Unable to sync file ${filePath}. Error is:${err.message}`.red.bold);
                    that.$logger.info("Try saving it again or restart the livesync operation.");
                }
            }));
        });
        this.$processService.attachToProcessExitSignals(this, () => {
            watcher.close(pattern);
        });
        this.$dispatcher.run();
    }
}
__decorate([
    helpers.hook('livesync')
], LiveSyncService.prototype, "liveSyncCore", null);
$injector.register("usbLiveSyncService", LiveSyncService);
