"use strict";
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 shelljs = require("shelljs");
const semver = require("semver");
const constants = require("../constants");
class PluginsService {
    constructor($npm, $fs, $options, $logger, $errors, $injector) {
        this.$npm = $npm;
        this.$fs = $fs;
        this.$options = $options;
        this.$logger = $logger;
        this.$errors = $errors;
        this.$injector = $injector;
    }
    get $projectData() {
        return this.$injector.resolve("projectData");
    }
    get $platformsData() {
        return this.$injector.resolve("platformsData");
    }
    get $pluginVariablesService() {
        return this.$injector.resolve("pluginVariablesService");
    }
    get $projectDataService() {
        return this.$injector.resolve("projectDataService");
    }
    get $projectFilesManager() {
        return this.$injector.resolve("projectFilesManager");
    }
    add(plugin) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.ensure();
            const possiblePackageName = path.resolve(plugin);
            if (possiblePackageName.indexOf(".tgz") !== -1 && this.$fs.exists(possiblePackageName)) {
                plugin = possiblePackageName;
            }
            let name = (yield this.$npm.install(plugin, this.$projectData.projectDir, PluginsService.NPM_CONFIG))[0];
            let pathToRealNpmPackageJson = path.join(this.$projectData.projectDir, "node_modules", name, "package.json");
            let realNpmPackageJson = this.$fs.readJson(pathToRealNpmPackageJson);
            if (realNpmPackageJson.nativescript) {
                let pluginData = this.convertToPluginData(realNpmPackageJson);
                let action = (pluginDestinationPath, platform, platformData) => __awaiter(this, void 0, void 0, function* () {
                    this.isPluginDataValidForPlatform(pluginData, platform);
                });
                this.executeForAllInstalledPlatforms(action);
                try {
                    yield this.$pluginVariablesService.savePluginVariablesInProjectFile(pluginData);
                }
                catch (err) {
                    this.$projectDataService.initialize(this.$projectData.projectDir);
                    this.$projectDataService.removeProperty(this.$pluginVariablesService.getPluginVariablePropertyName(pluginData.name));
                    yield this.$npm.uninstall(plugin, PluginsService.NPM_CONFIG, this.$projectData.projectDir);
                    throw err;
                }
                this.$logger.out(`Successfully installed plugin ${realNpmPackageJson.name}.`);
            }
            else {
                this.$npm.uninstall(realNpmPackageJson.name, { save: true }, this.$projectData.projectDir);
                this.$errors.failWithoutHelp(`${plugin} is not a valid NativeScript plugin. Verify that the plugin package.json file contains a nativescript key and try again.`);
            }
        });
    }
    remove(pluginName) {
        return __awaiter(this, void 0, void 0, function* () {
            let removePluginNativeCodeAction = (modulesDestinationPath, platform, platformData) => __awaiter(this, void 0, void 0, function* () {
                let pluginData = this.convertToPluginData(this.getNodeModuleData(pluginName));
                yield platformData.platformProjectService.removePluginNativeCode(pluginData);
            });
            this.$pluginVariablesService.removePluginVariablesFromProjectFile(pluginName.toLowerCase());
            this.executeForAllInstalledPlatforms(removePluginNativeCodeAction);
            yield this.executeNpmCommand(PluginsService.UNINSTALL_COMMAND_NAME, pluginName);
            let showMessage = true;
            let action = (modulesDestinationPath, platform, platformData) => __awaiter(this, void 0, void 0, function* () {
                shelljs.rm("-rf", path.join(modulesDestinationPath, pluginName));
                this.$logger.out(`Successfully removed plugin ${pluginName} for ${platform}.`);
                showMessage = false;
            });
            this.executeForAllInstalledPlatforms(action);
            if (showMessage) {
                this.$logger.out(`Succsessfully removed plugin ${pluginName}`);
            }
        });
    }
    getAvailable(filter) {
        let silent = true;
        return this.$npm.search(filter, { "silent": silent });
    }
    prepare(dependencyData, platform) {
        return __awaiter(this, void 0, void 0, function* () {
            platform = platform.toLowerCase();
            let platformData = this.$platformsData.getPlatformData(platform);
            let pluginData = this.convertToPluginData(dependencyData);
            let appFolderExists = this.$fs.exists(path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME));
            if (appFolderExists) {
                this.preparePluginScripts(pluginData, platform);
                yield this.preparePluginNativeCode(pluginData, platform);
                this.$logger.out(`Successfully prepared plugin ${pluginData.name} for ${platform}.`);
            }
        });
    }
    preparePluginScripts(pluginData, platform) {
        let platformData = this.$platformsData.getPlatformData(platform);
        let pluginScriptsDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules");
        let scriptsDestinationExists = this.$fs.exists(pluginScriptsDestinationPath);
        if (!scriptsDestinationExists) {
            return;
        }
        if (!this.isPluginDataValidForPlatform(pluginData, platform)) {
            return;
        }
        this.$projectFilesManager.processPlatformSpecificFiles(pluginScriptsDestinationPath, platform);
    }
    preparePluginNativeCode(pluginData, platform) {
        return __awaiter(this, void 0, void 0, function* () {
            let platformData = this.$platformsData.getPlatformData(platform);
            pluginData.pluginPlatformsFolderPath = (_platform) => path.join(pluginData.fullPath, "platforms", _platform);
            yield platformData.platformProjectService.preparePluginNativeCode(pluginData);
        });
    }
    ensureAllDependenciesAreInstalled() {
        return __awaiter(this, void 0, void 0, function* () {
            let installedDependencies = this.$fs.exists(this.nodeModulesPath) ? this.$fs.readDirectory(this.nodeModulesPath) : [];
            _(installedDependencies)
                .filter(dependencyName => _.startsWith(dependencyName, "@"))
                .each(scopedDependencyDir => {
                let contents = this.$fs.readDirectory(path.join(this.nodeModulesPath, scopedDependencyDir));
                installedDependencies = installedDependencies.concat(contents.map(dependencyName => `${scopedDependencyDir}/${dependencyName}`));
            });
            let packageJsonContent = this.$fs.readJson(this.getPackageJsonFilePath());
            let allDependencies = _.keys(packageJsonContent.dependencies).concat(_.keys(packageJsonContent.devDependencies));
            let notInstalledDependencies = _.difference(allDependencies, installedDependencies);
            if (this.$options.force || notInstalledDependencies.length) {
                this.$logger.trace("Npm install will be called from CLI. Force option is: ", this.$options.force, " Not installed dependencies are: ", notInstalledDependencies);
                yield this.$npm.install(this.$projectData.projectDir, this.$projectData.projectDir, { "ignore-scripts": this.$options.ignoreScripts });
            }
        });
    }
    getAllInstalledPlugins() {
        return __awaiter(this, void 0, void 0, function* () {
            let nodeModules = (yield this.getAllInstalledModules()).map(nodeModuleData => this.convertToPluginData(nodeModuleData));
            return _.filter(nodeModules, nodeModuleData => nodeModuleData && nodeModuleData.isPlugin);
        });
    }
    getDependenciesFromPackageJson() {
        let packageJson = this.$fs.readJson(this.getPackageJsonFilePath());
        let dependencies = this.getBasicPluginInformation(packageJson.dependencies);
        let devDependencies = this.getBasicPluginInformation(packageJson.devDependencies);
        return {
            dependencies,
            devDependencies
        };
    }
    getBasicPluginInformation(dependencies) {
        return _.map(dependencies, (version, key) => ({
            name: key,
            version: version
        }));
    }
    get nodeModulesPath() {
        return path.join(this.$projectData.projectDir, "node_modules");
    }
    getPackageJsonFilePath() {
        return path.join(this.$projectData.projectDir, "package.json");
    }
    getPackageJsonFilePathForModule(moduleName) {
        return path.join(this.nodeModulesPath, moduleName, "package.json");
    }
    getDependencies() {
        let packageJsonFilePath = this.getPackageJsonFilePath();
        return _.keys(require(packageJsonFilePath).dependencies);
    }
    getNodeModuleData(module) {
        if (!this.$fs.exists(module) || path.basename(module) !== "package.json") {
            module = this.getPackageJsonFilePathForModule(module);
        }
        let data = this.$fs.readJson(module);
        return {
            name: data.name,
            version: data.version,
            fullPath: path.dirname(module),
            isPlugin: data.nativescript !== undefined,
            moduleInfo: data.nativescript
        };
    }
    convertToPluginData(cacheData) {
        let pluginData = {};
        pluginData.name = cacheData.name;
        pluginData.version = cacheData.version;
        pluginData.fullPath = cacheData.directory || path.dirname(this.getPackageJsonFilePathForModule(cacheData.name));
        pluginData.isPlugin = !!cacheData.nativescript || !!cacheData.moduleInfo;
        pluginData.pluginPlatformsFolderPath = (platform) => path.join(pluginData.fullPath, "platforms", platform);
        let data = cacheData.nativescript || cacheData.moduleInfo;
        if (pluginData.isPlugin) {
            pluginData.platformsData = data.platforms;
            pluginData.pluginVariables = data.variables;
        }
        return pluginData;
    }
    ensure() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.ensureAllDependenciesAreInstalled();
            this.$fs.ensureDirectoryExists(this.nodeModulesPath);
        });
    }
    getAllInstalledModules() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.ensure();
            let nodeModules = this.getDependencies();
            return _.map(nodeModules, nodeModuleName => this.getNodeModuleData(nodeModuleName));
        });
    }
    executeNpmCommand(npmCommandName, npmCommandArguments) {
        return __awaiter(this, void 0, void 0, function* () {
            if (npmCommandName === PluginsService.INSTALL_COMMAND_NAME) {
                yield this.$npm.install(npmCommandArguments, this.$projectData.projectDir, PluginsService.NPM_CONFIG);
            }
            else if (npmCommandName === PluginsService.UNINSTALL_COMMAND_NAME) {
                yield this.$npm.uninstall(npmCommandArguments, PluginsService.NPM_CONFIG, this.$projectData.projectDir);
            }
            return this.parseNpmCommandResult(npmCommandArguments);
        });
    }
    parseNpmCommandResult(npmCommandResult) {
        return npmCommandResult.split("@")[0];
    }
    executeForAllInstalledPlatforms(action) {
        return __awaiter(this, void 0, void 0, function* () {
            let availablePlatforms = _.keys(this.$platformsData.availablePlatforms);
            for (let platform of availablePlatforms) {
                let isPlatformInstalled = this.$fs.exists(path.join(this.$projectData.platformsDir, platform.toLowerCase()));
                if (isPlatformInstalled) {
                    let platformData = this.$platformsData.getPlatformData(platform.toLowerCase());
                    let pluginDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules");
                    yield action(pluginDestinationPath, platform.toLowerCase(), platformData);
                }
            }
            ;
        });
    }
    getInstalledFrameworkVersion(platform) {
        let platformData = this.$platformsData.getPlatformData(platform);
        this.$projectDataService.initialize(this.$projectData.projectDir);
        let frameworkData = this.$projectDataService.getValue(platformData.frameworkPackageName);
        return frameworkData.version;
    }
    isPluginDataValidForPlatform(pluginData, platform) {
        let isValid = true;
        let installedFrameworkVersion = this.getInstalledFrameworkVersion(platform);
        let pluginPlatformsData = pluginData.platformsData;
        if (pluginPlatformsData) {
            let pluginVersion = pluginPlatformsData[platform];
            if (!pluginVersion) {
                this.$logger.warn(`${pluginData.name} is not supported for ${platform}.`);
                isValid = false;
            }
            else if (semver.gt(pluginVersion, installedFrameworkVersion)) {
                this.$logger.warn(`${pluginData.name} ${pluginVersion} for ${platform} is not compatible with the currently installed framework version ${installedFrameworkVersion}.`);
                isValid = false;
            }
        }
        return isValid;
    }
}
PluginsService.INSTALL_COMMAND_NAME = "install";
PluginsService.UNINSTALL_COMMAND_NAME = "uninstall";
PluginsService.NPM_CONFIG = {
    save: true
};
exports.PluginsService = PluginsService;
$injector.register("pluginsService", PluginsService);
