"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 path = require("path");
const shell = require("shelljs");
const constants = require("../constants");
const helpers = require("../common/helpers");
const semver = require("semver");
const app_files_updater_1 = require("./app-files-updater");
const temp = require("temp");
temp.track();
let clui = require("clui");
const buildInfoFileName = ".nsbuildinfo";
class PlatformService {
    constructor($devicesService, $errors, $fs, $logger, $npmInstallationManager, $platformsData, $projectData, $projectDataService, $hooksService, $options, $nodeModulesBuilder, $pluginsService, $projectFilesManager, $mobileHelper, $hostInfo, $xmlValidator, $npm, $sysInfo, $devicePlatformsConstants, $deviceAppDataFactory, $projectChangesService, $emulatorPlatformService, $analyticsService) {
        this.$devicesService = $devicesService;
        this.$errors = $errors;
        this.$fs = $fs;
        this.$logger = $logger;
        this.$npmInstallationManager = $npmInstallationManager;
        this.$platformsData = $platformsData;
        this.$projectData = $projectData;
        this.$projectDataService = $projectDataService;
        this.$hooksService = $hooksService;
        this.$options = $options;
        this.$nodeModulesBuilder = $nodeModulesBuilder;
        this.$pluginsService = $pluginsService;
        this.$projectFilesManager = $projectFilesManager;
        this.$mobileHelper = $mobileHelper;
        this.$hostInfo = $hostInfo;
        this.$xmlValidator = $xmlValidator;
        this.$npm = $npm;
        this.$sysInfo = $sysInfo;
        this.$devicePlatformsConstants = $devicePlatformsConstants;
        this.$deviceAppDataFactory = $deviceAppDataFactory;
        this.$projectChangesService = $projectChangesService;
        this.$emulatorPlatformService = $emulatorPlatformService;
        this.$analyticsService = $analyticsService;
        this._trackedProjectFilePath = null;
    }
    get _hooksService() {
        return this.$hooksService;
    }
    addPlatforms(platforms) {
        return __awaiter(this, void 0, void 0, function* () {
            let platformsDir = this.$projectData.platformsDir;
            this.$fs.ensureDirectoryExists(platformsDir);
            for (let platform of platforms) {
                yield this.addPlatform(platform.toLowerCase());
            }
        });
    }
    addPlatform(platformParam) {
        return __awaiter(this, void 0, void 0, function* () {
            let data = platformParam.split("@"), platform = data[0].toLowerCase(), version = data[1];
            this.validatePlatform(platform);
            let platformPath = path.join(this.$projectData.platformsDir, platform);
            if (this.$fs.exists(platformPath)) {
                this.$errors.failWithoutHelp("Platform %s already added", platform);
            }
            let platformData = this.$platformsData.getPlatformData(platform);
            let platformProjectService = platformData.platformProjectService;
            yield platformProjectService.validate();
            this.$logger.trace("Creating NativeScript project for the %s platform", platform);
            this.$logger.trace("Path: %s", platformData.projectRoot);
            this.$logger.trace("Package: %s", this.$projectData.projectId);
            this.$logger.trace("Name: %s", this.$projectData.projectName);
            this.$logger.out("Copying template files...");
            let packageToInstall = "";
            let npmOptions = {
                pathToSave: path.join(this.$projectData.platformsDir, platform),
                dependencyType: "save"
            };
            if (!this.$options.frameworkPath) {
                packageToInstall = platformData.frameworkPackageName;
                npmOptions["version"] = version;
            }
            let spinner = new clui.Spinner("Installing " + packageToInstall);
            let projectDir = this.$projectData.projectDir;
            try {
                spinner.start();
                let downloadedPackagePath = yield this.$npmInstallationManager.install(packageToInstall, projectDir, npmOptions);
                let frameworkDir = path.join(downloadedPackagePath, constants.PROJECT_FRAMEWORK_FOLDER_NAME);
                frameworkDir = path.resolve(frameworkDir);
                let coreModuleName = yield this.addPlatformCore(platformData, frameworkDir);
                yield this.$npm.uninstall(coreModuleName, { save: true }, this.$projectData.projectDir);
            }
            catch (err) {
                this.$fs.deleteDirectory(platformPath);
                throw err;
            }
            finally {
                spinner.stop();
            }
            this.$logger.out("Project successfully created.");
        });
    }
    addPlatformCore(platformData, frameworkDir) {
        return __awaiter(this, void 0, void 0, function* () {
            let coreModuleData = this.$fs.readJson(path.join(frameworkDir, "../", "package.json"));
            let installedVersion = coreModuleData.version;
            let coreModuleName = coreModuleData.name;
            this.$projectDataService.initialize(this.$projectData.projectDir);
            let customTemplateOptions = yield this.getPathToPlatformTemplate(this.$options.platformTemplate, platformData.frameworkPackageName);
            let pathToTemplate = customTemplateOptions && customTemplateOptions.pathToTemplate;
            yield platformData.platformProjectService.createProject(path.resolve(frameworkDir), installedVersion, pathToTemplate);
            platformData.platformProjectService.ensureConfigurationFileInAppResources();
            yield platformData.platformProjectService.interpolateData();
            platformData.platformProjectService.afterCreateProject(platformData.projectRoot);
            this.applyBaseConfigOption(platformData);
            let frameworkPackageNameData = { version: installedVersion };
            if (customTemplateOptions) {
                frameworkPackageNameData.template = customTemplateOptions.selectedTemplate;
            }
            this.$projectDataService.setValue(platformData.frameworkPackageName, frameworkPackageNameData);
            return coreModuleName;
        });
    }
    getPathToPlatformTemplate(selectedTemplate, frameworkPackageName) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!selectedTemplate) {
                let nativescriptPlatformData = this.$projectDataService.getValue(frameworkPackageName);
                selectedTemplate = nativescriptPlatformData && nativescriptPlatformData.template;
            }
            if (selectedTemplate) {
                let tempDir = temp.mkdirSync("platform-template");
                try {
                    let pathToTemplate = (yield this.$npm.install(selectedTemplate, tempDir))[0];
                    return { selectedTemplate, pathToTemplate };
                }
                catch (err) {
                    this.$logger.trace("Error while trying to install specified template: ", err);
                    this.$errors.failWithoutHelp(`Unable to install platform template ${selectedTemplate}. Make sure the specified value is valid.`);
                }
            }
            return null;
        });
    }
    getInstalledPlatforms() {
        if (!this.$fs.exists(this.$projectData.platformsDir)) {
            return [];
        }
        let subDirs = this.$fs.readDirectory(this.$projectData.platformsDir);
        return _.filter(subDirs, p => this.$platformsData.platformsNames.indexOf(p) > -1);
    }
    getAvailablePlatforms() {
        let installedPlatforms = this.getInstalledPlatforms();
        return _.filter(this.$platformsData.platformsNames, p => {
            return installedPlatforms.indexOf(p) < 0 && this.isPlatformSupportedForOS(p);
        });
    }
    getPreparedPlatforms() {
        return _.filter(this.$platformsData.platformsNames, p => { return this.isPlatformPrepared(p); });
    }
    preparePlatform(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            this.validatePlatform(platform);
            yield this.trackProjectType();
            try {
                yield this.$pluginsService.ensureAllDependenciesAreInstalled();
            }
            catch (err) {
                this.$logger.trace(err);
                this.$errors.failWithoutHelp(`Unable to install dependencies. Make sure your package.json is valid and all dependencies are correct. Error is: ${err.message}`);
            }
            if (platform === "ios") {
                for (let pluginData of yield this.$pluginsService.getAllInstalledPlugins()) {
                    if (this.$fs.exists(path.join(pluginData.pluginPlatformsFolderPath(platform), "Podfile")) &&
                        !(yield this.$sysInfo.getCocoapodVersion())) {
                        this.$errors.failWithoutHelp(`${pluginData.name} has Podfile and you don't have Cocoapods installed or it is not configured correctly. Please verify Cocoapods can work on your machine.`);
                    }
                }
            }
            yield this.ensurePlatformInstalled(platform);
            let changesInfo = this.$projectChangesService.checkForChanges(platform);
            this.$logger.trace("Changes info in prepare platform:", changesInfo);
            if (changesInfo.hasChanges) {
                yield this.preparePlatformCore(platform, changesInfo);
                this.$projectChangesService.savePrepareInfo(platform);
            }
            else {
                this.$logger.out("Skipping prepare.");
            }
            return true;
        });
    }
    validateOptions(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            if (platform) {
                platform = this.$mobileHelper.normalizePlatformName(platform);
                this.$logger.trace("Validate options for platform: " + platform);
                let platformData = this.$platformsData.getPlatformData(platform);
                return yield platformData.platformProjectService.validateOptions();
            }
            else {
                let valid = true;
                for (let availablePlatform in this.$platformsData.availablePlatforms) {
                    this.$logger.trace("Validate options for platform: " + availablePlatform);
                    let platformData = this.$platformsData.getPlatformData(availablePlatform);
                    valid = valid && (yield platformData.platformProjectService.validateOptions());
                }
                return valid;
            }
        });
    }
    preparePlatformCore(platform, changesInfo) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$logger.out("Preparing project...");
            let platformData = this.$platformsData.getPlatformData(platform);
            if (!changesInfo || changesInfo.appFilesChanged) {
                yield this.copyAppFiles(platform);
            }
            if (!changesInfo || changesInfo.appResourcesChanged) {
                this.copyAppResources(platform);
                yield platformData.platformProjectService.prepareProject();
            }
            if (!changesInfo || changesInfo.modulesChanged) {
                yield this.copyTnsModules(platform);
            }
            let directoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
            let excludedDirs = [constants.APP_RESOURCES_FOLDER_NAME];
            if (!changesInfo || !changesInfo.modulesChanged) {
                excludedDirs.push(constants.TNS_MODULES_FOLDER_NAME);
            }
            this.$projectFilesManager.processPlatformSpecificFiles(directoryPath, platform, excludedDirs);
            if (!changesInfo || changesInfo.configChanged || changesInfo.modulesChanged) {
                this.applyBaseConfigOption(platformData);
                yield platformData.platformProjectService.processConfigurationFilesFromAppResources();
            }
            yield platformData.platformProjectService.interpolateConfigurationFile();
            this.$logger.out("Project successfully prepared (" + platform + ")");
        });
    }
    copyAppFiles(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            let platformData = this.$platformsData.getPlatformData(platform);
            platformData.platformProjectService.ensureConfigurationFileInAppResources();
            let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
            this.$fs.ensureDirectoryExists(appDestinationDirectoryPath);
            let appSourceDirectoryPath = path.join(this.$projectData.projectDir, constants.APP_FOLDER_NAME);
            const appUpdater = new app_files_updater_1.AppFilesUpdater(appSourceDirectoryPath, appDestinationDirectoryPath, this.$options, this.$fs);
            appUpdater.updateApp(sourceFiles => {
                this.$xmlValidator.validateXmlFiles(sourceFiles);
            });
        });
    }
    copyAppResources(platform) {
        let platformData = this.$platformsData.getPlatformData(platform);
        let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
        let appResourcesDirectoryPath = path.join(appDestinationDirectoryPath, constants.APP_RESOURCES_FOLDER_NAME);
        if (this.$fs.exists(appResourcesDirectoryPath)) {
            platformData.platformProjectService.prepareAppResources(appResourcesDirectoryPath);
            let appResourcesDestination = platformData.platformProjectService.getAppResourcesDestinationDirectoryPath();
            this.$fs.ensureDirectoryExists(appResourcesDestination);
            shell.cp("-Rf", path.join(appResourcesDirectoryPath, platformData.normalizedPlatformName, "*"), appResourcesDestination);
            this.$fs.deleteDirectory(appResourcesDirectoryPath);
        }
    }
    copyTnsModules(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            let platformData = this.$platformsData.getPlatformData(platform);
            let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
            let lastModifiedTime = this.$fs.exists(appDestinationDirectoryPath) ? this.$fs.getFsStats(appDestinationDirectoryPath).mtime : null;
            try {
                let tnsModulesDestinationPath = path.join(appDestinationDirectoryPath, constants.TNS_MODULES_FOLDER_NAME);
                yield this.$nodeModulesBuilder.prepareNodeModules(tnsModulesDestinationPath, platform, lastModifiedTime);
            }
            catch (error) {
                this.$logger.debug(error);
                shell.rm("-rf", appDestinationDirectoryPath);
                this.$errors.failWithoutHelp(`Processing node_modules failed. ${error}`);
            }
        });
    }
    shouldBuild(platform, buildConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.$projectChangesService.currentChanges.changesRequireBuild) {
                return true;
            }
            let platformData = this.$platformsData.getPlatformData(platform);
            let forDevice = !buildConfig || buildConfig.buildForDevice;
            let outputPath = forDevice ? platformData.deviceBuildOutputPath : platformData.emulatorBuildOutputPath;
            if (!this.$fs.exists(outputPath)) {
                return true;
            }
            let packageNames = forDevice ? platformData.validPackageNamesForDevice : platformData.validPackageNamesForEmulator;
            let packages = this.getApplicationPackages(outputPath, packageNames);
            if (packages.length === 0) {
                return true;
            }
            let prepareInfo = this.$projectChangesService.getPrepareInfo(platform);
            let buildInfo = this.getBuildInfo(platform, platformData, buildConfig);
            if (!prepareInfo || !buildInfo) {
                return true;
            }
            if (this.$options.clean) {
                return prepareInfo.time !== buildInfo.prepareTime;
            }
            if (prepareInfo.time === buildInfo.prepareTime) {
                return false;
            }
            return prepareInfo.changesRequireBuildTime !== buildInfo.prepareTime;
        });
    }
    trackProjectType() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.$projectData && (this.$projectData.projectFilePath !== this._trackedProjectFilePath)) {
                this._trackedProjectFilePath = this.$projectData.projectFilePath;
                yield this.$analyticsService.track("Working with project type", this.$projectData.projectType);
            }
        });
    }
    buildPlatform(platform, buildConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$logger.out("Building project...");
            yield this.trackProjectType();
            let platformData = this.$platformsData.getPlatformData(platform);
            yield platformData.platformProjectService.buildProject(platformData.projectRoot, buildConfig);
            let prepareInfo = this.$projectChangesService.getPrepareInfo(platform);
            let buildInfoFilePath = this.getBuildOutputPath(platform, platformData, buildConfig);
            let buildInfoFile = path.join(buildInfoFilePath, buildInfoFileName);
            let buildInfo = {
                prepareTime: prepareInfo.changesRequireBuildTime,
                buildTime: new Date().toString()
            };
            this.$fs.writeJson(buildInfoFile, buildInfo);
            this.$logger.out("Project successfully built.");
        });
    }
    shouldInstall(device) {
        return __awaiter(this, void 0, void 0, function* () {
            let platform = device.deviceInfo.platform;
            let platformData = this.$platformsData.getPlatformData(platform);
            if (!(yield device.applicationManager.isApplicationInstalled(this.$projectData.projectId))) {
                return true;
            }
            let deviceBuildInfo = yield this.getDeviceBuildInfo(device);
            let localBuildInfo = this.getBuildInfo(platform, platformData, { buildForDevice: !device.isEmulator });
            return !localBuildInfo || !deviceBuildInfo || deviceBuildInfo.buildTime !== localBuildInfo.buildTime;
        });
    }
    installApplication(device) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$logger.out("Installing...");
            let platformData = this.$platformsData.getPlatformData(device.deviceInfo.platform);
            let packageFile = "";
            if (this.$devicesService.isiOSSimulator(device)) {
                packageFile = this.getLatestApplicationPackageForEmulator(platformData).packageName;
            }
            else {
                packageFile = this.getLatestApplicationPackageForDevice(platformData).packageName;
            }
            yield platformData.platformProjectService.deploy(device.deviceInfo.identifier);
            yield device.applicationManager.reinstallApplication(this.$projectData.projectId, packageFile);
            if (!this.$options.release) {
                let deviceFilePath = yield this.getDeviceBuildInfoFilePath(device);
                let buildInfoFilePath = this.getBuildOutputPath(device.deviceInfo.platform, platformData, { buildForDevice: !device.isEmulator });
                let appIdentifier = this.$projectData.projectId;
                yield device.fileSystem.putFile(path.join(buildInfoFilePath, buildInfoFileName), deviceFilePath, appIdentifier);
            }
            this.$logger.out(`Successfully installed on device with identifier '${device.deviceInfo.identifier}'.`);
        });
    }
    deployPlatform(platform, forceInstall) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.preparePlatform(platform);
            this.$logger.out("Searching for devices...");
            yield this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device });
            let action = (device) => __awaiter(this, void 0, void 0, function* () {
                let buildConfig = { buildForDevice: !this.$devicesService.isiOSSimulator(device) };
                let shouldBuild = yield this.shouldBuild(platform, buildConfig);
                if (shouldBuild) {
                    yield this.buildPlatform(platform, buildConfig);
                }
                else {
                    this.$logger.out("Skipping package build. No changes detected on the native side. This will be fast!");
                }
                if (forceInstall || shouldBuild || (yield this.shouldInstall(device))) {
                    yield this.installApplication(device);
                }
                else {
                    this.$logger.out("Skipping install.");
                }
            });
            yield this.$devicesService.execute(action, this.getCanExecuteAction(platform));
        });
    }
    runPlatform(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.trackProjectType();
            if (this.$options.justlaunch) {
                this.$options.watch = false;
            }
            this.$logger.out("Starting...");
            let action = (device) => __awaiter(this, void 0, void 0, function* () {
                yield device.applicationManager.startApplication(this.$projectData.projectId);
                this.$logger.out(`Successfully started on device with identifier '${device.deviceInfo.identifier}'.`);
            });
            yield this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device });
            yield this.$devicesService.execute(action, this.getCanExecuteAction(platform));
        });
    }
    emulatePlatform(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.$options.avd) {
                this.$logger.warn(`Option --avd is no longer supported. Please use --device instead!`);
                return Promise.resolve();
            }
            if (this.$options.availableDevices) {
                return this.$emulatorPlatformService.listAvailableEmulators(platform);
            }
            this.$options.emulator = true;
            if (this.$options.device) {
                let info = yield this.$emulatorPlatformService.getEmulatorInfo(platform, this.$options.device);
                if (info) {
                    if (!info.isRunning) {
                        yield this.$emulatorPlatformService.startEmulator(info);
                    }
                    this.$options.device = null;
                }
                else {
                    yield this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device });
                    let found = [];
                    if (this.$devicesService.hasDevices) {
                        found = this.$devicesService.getDevices().filter((device) => device.identifier === this.$options.device);
                    }
                    if (found.length === 0) {
                        this.$errors.fail("Cannot find device with name: %s", this.$options.device);
                    }
                }
            }
            yield this.deployPlatform(platform);
            return this.runPlatform(platform);
        });
    }
    getBuildOutputPath(platform, platformData, buildConfig) {
        let buildForDevice = buildConfig ? buildConfig.buildForDevice : this.$options.forDevice;
        if (platform.toLowerCase() === this.$devicePlatformsConstants.iOS.toLowerCase()) {
            return buildForDevice ? platformData.deviceBuildOutputPath : platformData.emulatorBuildOutputPath;
        }
        return platformData.deviceBuildOutputPath;
    }
    getDeviceBuildInfoFilePath(device) {
        return __awaiter(this, void 0, void 0, function* () {
            let deviceAppData = this.$deviceAppDataFactory.create(this.$projectData.projectId, device.deviceInfo.platform, device);
            let deviceRootPath = path.dirname(yield deviceAppData.getDeviceProjectRootPath());
            return helpers.fromWindowsRelativePathToUnix(path.join(deviceRootPath, buildInfoFileName));
        });
    }
    getDeviceBuildInfo(device) {
        return __awaiter(this, void 0, void 0, function* () {
            let deviceFilePath = yield this.getDeviceBuildInfoFilePath(device);
            try {
                return JSON.parse(yield this.readFile(device, deviceFilePath));
            }
            catch (e) {
                return null;
            }
        });
    }
    getBuildInfo(platform, platformData, buildConfig) {
        let buildInfoFilePath = this.getBuildOutputPath(platform, platformData, buildConfig);
        let buildInfoFile = path.join(buildInfoFilePath, buildInfoFileName);
        if (this.$fs.exists(buildInfoFile)) {
            try {
                let buildInfoTime = this.$fs.readJson(buildInfoFile);
                return buildInfoTime;
            }
            catch (e) {
                return null;
            }
        }
        return null;
    }
    cleanDestinationApp(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.ensurePlatformInstalled(platform);
            const appSourceDirectoryPath = path.join(this.$projectData.projectDir, constants.APP_FOLDER_NAME);
            let platformData = this.$platformsData.getPlatformData(platform);
            let appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
            const appUpdater = new app_files_updater_1.AppFilesUpdater(appSourceDirectoryPath, appDestinationDirectoryPath, this.$options, this.$fs);
            appUpdater.cleanDestinationApp();
        });
    }
    lastOutputPath(platform, settings) {
        let packageFile;
        let platformData = this.$platformsData.getPlatformData(platform);
        if (settings.isForDevice) {
            packageFile = this.getLatestApplicationPackageForDevice(platformData).packageName;
        }
        else {
            packageFile = this.getLatestApplicationPackageForEmulator(platformData).packageName;
        }
        if (!packageFile || !this.$fs.exists(packageFile)) {
            this.$errors.failWithoutHelp("Unable to find built application. Try 'tns build %s'.", platform);
        }
        return packageFile;
    }
    copyLastOutput(platform, targetPath, settings) {
        platform = platform.toLowerCase();
        targetPath = path.resolve(targetPath);
        let packageFile = this.lastOutputPath(platform, settings);
        this.$fs.ensureDirectoryExists(path.dirname(targetPath));
        if (this.$fs.exists(targetPath) && this.$fs.getFsStats(targetPath).isDirectory()) {
            let sourceFileName = path.basename(packageFile);
            this.$logger.trace(`Specified target path: '${targetPath}' is directory. Same filename will be used: '${sourceFileName}'.`);
            targetPath = path.join(targetPath, sourceFileName);
        }
        this.$fs.copyFile(packageFile, targetPath);
        this.$logger.info(`Copied file '${packageFile}' to '${targetPath}'.`);
    }
    removePlatforms(platforms) {
        this.$projectDataService.initialize(this.$projectData.projectDir);
        _.each(platforms, platform => {
            this.validatePlatformInstalled(platform);
            let platformData = this.$platformsData.getPlatformData(platform);
            let platformDir = path.join(this.$projectData.platformsDir, platform);
            this.$fs.deleteDirectory(platformDir);
            this.$projectDataService.removeProperty(platformData.frameworkPackageName);
            this.$logger.out(`Platform ${platform} successfully removed.`);
        });
    }
    updatePlatforms(platforms) {
        return __awaiter(this, void 0, void 0, function* () {
            for (let platformParam of platforms) {
                let data = platformParam.split("@"), platform = data[0], version = data[1];
                if (this.isPlatformInstalled(platform)) {
                    yield this.updatePlatform(platform, version);
                }
                else {
                    yield this.addPlatform(platformParam);
                }
            }
            ;
        });
    }
    getCanExecuteAction(platform) {
        let canExecute = (currentDevice) => {
            if (this.$options.device && currentDevice && currentDevice.deviceInfo) {
                let device = this.$devicesService.getDeviceByDeviceOption();
                if (device && device.deviceInfo) {
                    return currentDevice.deviceInfo.identifier === device.deviceInfo.identifier;
                }
            }
            if (this.$mobileHelper.isiOSPlatform(platform) && this.$hostInfo.isDarwin) {
                if (this.$devicesService.isOnlyiOSSimultorRunning() || this.$options.emulator || this.$devicesService.isiOSSimulator(currentDevice)) {
                    return true;
                }
                return this.$devicesService.isiOSDevice(currentDevice);
            }
            return true;
        };
        return canExecute;
    }
    validatePlatform(platform) {
        if (!platform) {
            this.$errors.fail("No platform specified.");
        }
        platform = platform.split("@")[0].toLowerCase();
        if (!this.isValidPlatform(platform)) {
            this.$errors.fail("Invalid platform %s. Valid platforms are %s.", platform, helpers.formatListOfNames(this.$platformsData.platformsNames));
        }
        if (!this.isPlatformSupportedForOS(platform)) {
            this.$errors.fail("Applications for platform %s can not be built on this OS - %s", platform, process.platform);
        }
    }
    validatePlatformInstalled(platform) {
        this.validatePlatform(platform);
        if (!this.isPlatformInstalled(platform)) {
            this.$errors.fail("The platform %s is not added to this project. Please use 'tns platform add <platform>'", platform);
        }
    }
    ensurePlatformInstalled(platform) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.isPlatformInstalled(platform)) {
                yield this.addPlatform(platform);
            }
        });
    }
    isPlatformInstalled(platform) {
        return this.$fs.exists(path.join(this.$projectData.platformsDir, platform.toLowerCase()));
    }
    isValidPlatform(platform) {
        return this.$platformsData.getPlatformData(platform);
    }
    isPlatformSupportedForOS(platform) {
        let targetedOS = this.$platformsData.getPlatformData(platform).targetedOS;
        let res = !targetedOS || targetedOS.indexOf("*") >= 0 || targetedOS.indexOf(process.platform) >= 0;
        return res;
    }
    isPlatformPrepared(platform) {
        let platformData = this.$platformsData.getPlatformData(platform);
        return platformData.platformProjectService.isPlatformPrepared(platformData.projectRoot);
    }
    getApplicationPackages(buildOutputPath, validPackageNames) {
        let candidates = this.$fs.readDirectory(buildOutputPath);
        let packages = _.filter(candidates, candidate => {
            return _.includes(validPackageNames, candidate);
        }).map(currentPackage => {
            currentPackage = path.join(buildOutputPath, currentPackage);
            return {
                packageName: currentPackage,
                time: this.$fs.getFsStats(currentPackage).mtime
            };
        });
        return packages;
    }
    getLatestApplicationPackage(buildOutputPath, validPackageNames) {
        let packages = this.getApplicationPackages(buildOutputPath, validPackageNames);
        if (packages.length === 0) {
            let packageExtName = path.extname(validPackageNames[0]);
            this.$errors.fail("No %s found in %s directory", packageExtName, buildOutputPath);
        }
        packages = _.sortBy(packages, pkg => pkg.time).reverse();
        return packages[0];
    }
    getLatestApplicationPackageForDevice(platformData) {
        return this.getLatestApplicationPackage(platformData.deviceBuildOutputPath, platformData.validPackageNamesForDevice);
    }
    getLatestApplicationPackageForEmulator(platformData) {
        return this.getLatestApplicationPackage(platformData.emulatorBuildOutputPath || platformData.deviceBuildOutputPath, platformData.validPackageNamesForEmulator || platformData.validPackageNamesForDevice);
    }
    updatePlatform(platform, version) {
        return __awaiter(this, void 0, void 0, function* () {
            let platformData = this.$platformsData.getPlatformData(platform);
            this.$projectDataService.initialize(this.$projectData.projectDir);
            let data = this.$projectDataService.getValue(platformData.frameworkPackageName);
            let currentVersion = data && data.version ? data.version : "0.2.0";
            let newVersion = version === constants.PackageVersion.NEXT ?
                yield this.$npmInstallationManager.getNextVersion(platformData.frameworkPackageName) :
                version || (yield this.$npmInstallationManager.getLatestCompatibleVersion(platformData.frameworkPackageName));
            let installedModuleDir = yield this.$npmInstallationManager.install(platformData.frameworkPackageName, this.$projectData.projectDir, { version: newVersion, dependencyType: "save" });
            let cachedPackageData = this.$fs.readJson(path.join(installedModuleDir, "package.json"));
            newVersion = (cachedPackageData && cachedPackageData.version) || newVersion;
            let canUpdate = platformData.platformProjectService.canUpdatePlatform(installedModuleDir);
            yield this.$npm.uninstall(platformData.frameworkPackageName, { save: true }, this.$projectData.projectDir);
            if (canUpdate) {
                if (!semver.valid(newVersion)) {
                    this.$errors.fail("The version %s is not valid. The version should consists from 3 parts separated by dot.", newVersion);
                }
                if (!semver.gt(currentVersion, newVersion)) {
                    yield this.updatePlatformCore(platformData, currentVersion, newVersion, canUpdate);
                }
                else if (semver.eq(currentVersion, newVersion)) {
                    this.$errors.fail("Current and new version are the same.");
                }
                else {
                    this.$errors.fail(`Your current version: ${currentVersion} is higher than the one you're trying to install ${newVersion}.`);
                }
            }
            else {
                this.$errors.failWithoutHelp("Native Platform cannot be updated.");
            }
        });
    }
    updatePlatformCore(platformData, currentVersion, newVersion, canUpdate) {
        return __awaiter(this, void 0, void 0, function* () {
            let packageName = platformData.normalizedPlatformName.toLowerCase();
            this.removePlatforms([packageName]);
            packageName = newVersion ? `${packageName}@${newVersion}` : packageName;
            yield this.addPlatform(packageName);
            this.$logger.out("Successfully updated to version ", newVersion);
        });
    }
    applyBaseConfigOption(platformData) {
        if (this.$options.baseConfig) {
            let newConfigFile = path.resolve(this.$options.baseConfig);
            this.$logger.trace(`Replacing '${platformData.configurationFilePath}' with '${newConfigFile}'.`);
            this.$fs.copyFile(newConfigFile, platformData.configurationFilePath);
        }
    }
    readFile(device, deviceFilePath) {
        return __awaiter(this, void 0, void 0, function* () {
            temp.track();
            let uniqueFilePath = temp.path({ suffix: ".tmp" });
            try {
                yield device.fileSystem.getFile(deviceFilePath, this.$projectData.projectId, uniqueFilePath);
            }
            catch (e) {
                return null;
            }
            if (this.$fs.exists(uniqueFilePath)) {
                let text = this.$fs.readText(uniqueFilePath);
                shell.rm(uniqueFilePath);
                return text;
            }
            return null;
        });
    }
}
__decorate([
    helpers.hook('prepare')
], PlatformService.prototype, "preparePlatformCore", null);
exports.PlatformService = PlatformService;
$injector.register("platformService", PlatformService);
