"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;
};
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");
const Future = require("fibers/future");
temp.track();
let clui = require("clui");
const buildInfoFileName = ".nsbuildinfo";
class PlatformService {
    constructor($devicesService, $errors, $fs, $logger, $npmInstallationManager, $platformsData, $projectData, $projectDataService, $prompter, $hooksService, $commandsService, $options, $nodeModulesBuilder, $pluginsService, $projectFilesManager, $mobileHelper, $hostInfo, $xmlValidator, $npm, $sysInfo, $staticConfig, $devicePlatformsConstants, $deviceAppDataFactory, $projectChangesService, $emulatorPlatformService, $childProcess) {
        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.$prompter = $prompter;
        this.$hooksService = $hooksService;
        this.$commandsService = $commandsService;
        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.$staticConfig = $staticConfig;
        this.$devicePlatformsConstants = $devicePlatformsConstants;
        this.$deviceAppDataFactory = $deviceAppDataFactory;
        this.$projectChangesService = $projectChangesService;
        this.$emulatorPlatformService = $emulatorPlatformService;
        this.$childProcess = $childProcess;
    }
    addPlatforms(platforms) {
        return (() => {
            let platformsDir = this.$projectData.platformsDir;
            this.$fs.ensureDirectoryExists(platformsDir);
            _.each(platforms, platform => {
                this.addPlatform(platform.toLowerCase()).wait();
            });
        }).future()();
    }
    addPlatform(platformParam) {
        return (() => {
            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;
            platformProjectService.validate().wait();
            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);
            try {
                spinner.start();
                let downloadedPackagePath = this.$npmInstallationManager.install(packageToInstall, this.$projectData.projectDir, npmOptions).wait();
                let frameworkDir = path.join(downloadedPackagePath, constants.PROJECT_FRAMEWORK_FOLDER_NAME);
                frameworkDir = path.resolve(frameworkDir);
                let coreModuleName = this.addPlatformCore(platformData, frameworkDir).wait();
                this.$npm.uninstall(coreModuleName, { save: true }, this.$projectData.projectDir).wait();
            }
            catch (err) {
                this.$fs.deleteDirectory(platformPath);
                throw err;
            }
            finally {
                spinner.stop();
            }
            this.$logger.out("Project successfully created.");
        }).future()();
    }
    addPlatformCore(platformData, frameworkDir) {
        return (() => {
            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 = this.getPathToPlatformTemplate(this.$options.platformTemplate, platformData.frameworkPackageName).wait();
            let pathToTemplate = customTemplateOptions && customTemplateOptions.pathToTemplate;
            platformData.platformProjectService.createProject(path.resolve(frameworkDir), installedVersion, pathToTemplate).wait();
            platformData.platformProjectService.ensureConfigurationFileInAppResources();
            platformData.platformProjectService.interpolateData().wait();
            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;
        }).future()();
    }
    getPathToPlatformTemplate(selectedTemplate, frameworkPackageName) {
        return (() => {
            if (!selectedTemplate) {
                let nativescriptPlatformData = this.$projectDataService.getValue(frameworkPackageName);
                selectedTemplate = nativescriptPlatformData && nativescriptPlatformData.template;
            }
            if (selectedTemplate) {
                let tempDir = temp.mkdirSync("platform-template");
                try {
                    let pathToTemplate = this.$npm.install(selectedTemplate, tempDir).wait()[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;
        }).future()();
    }
    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 (() => {
            this.validatePlatform(platform);
            try {
                this.$pluginsService.ensureAllDependenciesAreInstalled().wait();
            }
            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") {
                _.each(this.$pluginsService.getAllInstalledPlugins().wait(), (pluginData) => {
                    if (this.$fs.exists(path.join(pluginData.pluginPlatformsFolderPath(platform), "Podfile")) &&
                        !this.$sysInfo.getCocoapodVersion().wait()) {
                        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.`);
                    }
                });
            }
            this.ensurePlatformInstalled(platform).wait();
            let changesInfo = this.$projectChangesService.checkForChanges(platform);
            if (changesInfo.hasChanges) {
                this.preparePlatformCore(platform, changesInfo).wait();
                this.$projectChangesService.savePrepareInfo(platform);
            }
            else {
                this.$logger.out("Skipping prepare.");
            }
            return true;
        }).future()();
    }
    validateOptions(platform) {
        return (() => {
            if (platform) {
                platform = this.$mobileHelper.normalizePlatformName(platform);
                this.$logger.trace("Validate options for platform: " + platform);
                let platformData = this.$platformsData.getPlatformData(platform);
                return platformData.platformProjectService.validateOptions().wait();
            }
            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 && platformData.platformProjectService.validateOptions().wait();
                }
                return valid;
            }
        }).future()();
    }
    preparePlatformCore(platform, changesInfo) {
        return (() => {
            this.$logger.out("Preparing project...");
            let platformData = this.$platformsData.getPlatformData(platform);
            if (!changesInfo || changesInfo.appFilesChanged) {
                this.copyAppFiles(platform).wait();
            }
            if (!changesInfo || changesInfo.appResourcesChanged) {
                this.copyAppResources(platform);
                platformData.platformProjectService.prepareProject();
            }
            if (!changesInfo || changesInfo.modulesChanged) {
                this.copyTnsModules(platform).wait();
            }
            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);
                platformData.platformProjectService.processConfigurationFilesFromAppResources().wait();
            }
            platformData.platformProjectService.interpolateConfigurationFile().wait();
            this.$logger.out("Project successfully prepared (" + platform + ")");
        }).future()();
    }
    copyAppFiles(platform) {
        return (() => {
            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);
            });
        }).future()();
    }
    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 (() => {
            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);
                this.$nodeModulesBuilder.prepareNodeModules(tnsModulesDestinationPath, platform, lastModifiedTime).wait();
            }
            catch (error) {
                this.$logger.debug(error);
                shell.rm("-rf", appDestinationDirectoryPath);
                this.$errors.failWithoutHelp(`Processing node_modules failed. ${error}`);
            }
        }).future()();
    }
    shouldBuild(platform, buildConfig) {
        return (() => {
            if (this.$options.release || 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;
        }).future()();
    }
    buildPlatform(platform, buildConfig) {
        return (() => {
            this.$logger.out("Building project...");
            let platformData = this.$platformsData.getPlatformData(platform);
            platformData.platformProjectService.buildProject(platformData.projectRoot, buildConfig).wait();
            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.");
        }).future()();
    }
    shouldInstall(device) {
        let platform = device.deviceInfo.platform;
        let platformData = this.$platformsData.getPlatformData(platform);
        if (!device.applicationManager.isApplicationInstalled(this.$projectData.projectId).wait()) {
            return true;
        }
        let deviceBuildInfo = this.getDeviceBuildInfo(device).wait();
        let localBuildInfo = this.getBuildInfo(platform, platformData, { buildForDevice: !device.isEmulator });
        return !localBuildInfo || !deviceBuildInfo || deviceBuildInfo.buildTime !== localBuildInfo.buildTime;
    }
    installApplication(device) {
        return (() => {
            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;
            }
            platformData.platformProjectService.deploy(device.deviceInfo.identifier).wait();
            device.applicationManager.reinstallApplication(this.$projectData.projectId, packageFile).wait();
            if (!this.$options.release) {
                let deviceFilePath = this.getDeviceBuildInfoFilePath(device);
                let buildInfoFilePath = this.getBuildOutputPath(device.deviceInfo.platform, platformData, { buildForDevice: !device.isEmulator });
                device.fileSystem.putFile(path.join(buildInfoFilePath, buildInfoFileName), deviceFilePath).wait();
            }
            this.$logger.out(`Successfully installed on device with identifier '${device.deviceInfo.identifier}'.`);
        }).future()();
    }
    deployPlatform(platform, forceInstall) {
        return (() => {
            this.preparePlatform(platform).wait();
            this.$logger.out("Searching for devices...");
            this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device }).wait();
            let action = (device) => {
                return (() => {
                    let buildConfig = { buildForDevice: !this.$devicesService.isiOSSimulator(device) };
                    let shouldBuild = this.shouldBuild(platform, buildConfig).wait();
                    if (shouldBuild) {
                        this.buildPlatform(platform, buildConfig).wait();
                    }
                    else {
                        this.$logger.out("Skipping package build. No changes detected on the native side. This will be fast!");
                    }
                    if (forceInstall || shouldBuild || this.shouldInstall(device)) {
                        this.installApplication(device).wait();
                    }
                    else {
                        this.$logger.out("Skipping install.");
                    }
                }).future()();
            };
            this.$devicesService.execute(action, this.getCanExecuteAction(platform)).wait();
        }).future()();
    }
    runPlatform(platform) {
        return (() => {
            this.$logger.out("Starting...");
            let action = (device) => {
                return (() => {
                    device.applicationManager.startApplication(this.$projectData.projectId).wait();
                    this.$logger.out(`Successfully started on device with identifier '${device.deviceInfo.identifier}'.`);
                }).future()();
            };
            this.$devicesService.initialize({ platform: platform, deviceId: this.$options.device }).wait();
            this.$devicesService.execute(action, this.getCanExecuteAction(platform)).wait();
        }).future()();
    }
    emulatePlatform(platform) {
        if (this.$options.avd) {
            this.$logger.warn(`Option --avd is no longer supported. Please use --device instead!`);
            return Future.fromResult();
        }
        if (this.$options.availableDevices) {
            return this.$emulatorPlatformService.listAvailableEmulators(platform);
        }
        if (this.$options.device) {
            let info = this.$emulatorPlatformService.getEmulatorInfo(platform, this.$options.device).wait();
            if (info) {
                if (!info.isRunning) {
                    this.$emulatorPlatformService.startEmulator(info).wait();
                }
                this.$options.device = null;
            }
        }
        this.$options.emulator = true;
        this.deployPlatform(platform).wait();
        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) {
        let deviceAppData = this.$deviceAppDataFactory.create(this.$projectData.projectId, device.deviceInfo.platform, device);
        let deviceRootPath = deviceAppData.deviceProjectRootPath;
        if (device.deviceInfo.platform.toLowerCase() === this.$devicePlatformsConstants.Android.toLowerCase()) {
            deviceRootPath = path.dirname(deviceRootPath);
        }
        return path.join(deviceRootPath, buildInfoFileName);
    }
    getDeviceBuildInfo(device) {
        return (() => {
            let deviceFilePath = this.getDeviceBuildInfoFilePath(device);
            try {
                return JSON.parse(this.readFile(device, deviceFilePath).wait());
            }
            catch (e) {
                return null;
            }
            ;
        }).future()();
    }
    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 (() => {
            this.ensurePlatformInstalled(platform).wait();
            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();
        }).future()();
    }
    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 (() => {
            _.each(platforms, platformParam => {
                let data = platformParam.split("@"), platform = data[0], version = data[1];
                if (this.isPlatformInstalled(platform)) {
                    this.updatePlatform(platform, version).wait();
                }
                else {
                    this.addPlatform(platformParam).wait();
                }
            });
        }).future()();
    }
    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 (() => {
            if (!this.isPlatformInstalled(platform)) {
                this.addPlatform(platform).wait();
            }
        }).future()();
    }
    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 (() => {
            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 ?
                this.$npmInstallationManager.getNextVersion(platformData.frameworkPackageName).wait() :
                version || this.$npmInstallationManager.getLatestCompatibleVersion(platformData.frameworkPackageName).wait();
            let installedModuleDir = this.$npmInstallationManager.install(platformData.frameworkPackageName, this.$projectData.projectDir, { version: newVersion, dependencyType: "save" }).wait();
            let cachedPackageData = this.$fs.readJson(path.join(installedModuleDir, "package.json"));
            newVersion = (cachedPackageData && cachedPackageData.version) || newVersion;
            let canUpdate = platformData.platformProjectService.canUpdatePlatform(installedModuleDir);
            this.$npm.uninstall(platformData.frameworkPackageName, { save: true }, this.$projectData.projectDir).wait();
            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)) {
                    this.updatePlatformCore(platformData, currentVersion, newVersion, canUpdate).wait();
                }
                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.");
            }
        }).future()();
    }
    updatePlatformCore(platformData, currentVersion, newVersion, canUpdate) {
        return (() => {
            let packageName = platformData.normalizedPlatformName.toLowerCase();
            this.removePlatforms([packageName]);
            packageName = newVersion ? `${packageName}@${newVersion}` : packageName;
            this.addPlatform(packageName).wait();
            this.$logger.out("Successfully updated to version ", newVersion);
        }).future()();
    }
    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 (() => {
            temp.track();
            let uniqueFilePath = temp.path({ suffix: ".tmp" });
            try {
                device.fileSystem.getFile(deviceFilePath, uniqueFilePath).wait();
            }
            catch (e) {
                return null;
            }
            if (this.$fs.exists(uniqueFilePath)) {
                let text = this.$fs.readText(uniqueFilePath);
                shell.rm(uniqueFilePath);
                return text;
            }
            return null;
        }).future()();
    }
}
__decorate([
    helpers.hook('prepare')
], PlatformService.prototype, "preparePlatformCore", null);
exports.PlatformService = PlatformService;
$injector.register("platformService", PlatformService);
