"use strict";
const path = require("path");
const temp = require("temp");
const constants = require("../constants");
temp.track();
class ProjectTemplatesService {
    constructor($errors, $fs, $logger, $npm, $npmInstallationManager) {
        this.$errors = $errors;
        this.$fs = $fs;
        this.$logger = $logger;
        this.$npm = $npm;
        this.$npmInstallationManager = $npmInstallationManager;
    }
    prepareTemplate(originalTemplateName, projectDir) {
        return (() => {
            let realTemplatePath;
            if (originalTemplateName) {
                let data = originalTemplateName.split("@"), name = data[0], version = data[1];
                if (constants.RESERVED_TEMPLATE_NAMES[name.toLowerCase()]) {
                    realTemplatePath = this.prepareNativeScriptTemplate(constants.RESERVED_TEMPLATE_NAMES[name.toLowerCase()], version, projectDir).wait();
                }
                else {
                    realTemplatePath = this.prepareNativeScriptTemplate(name, version, projectDir).wait();
                }
            }
            else {
                realTemplatePath = this.prepareNativeScriptTemplate(constants.RESERVED_TEMPLATE_NAMES["default"], null, projectDir).wait();
            }
            if (realTemplatePath) {
                this.$fs.deleteDirectory(path.join(realTemplatePath, constants.NODE_MODULES_FOLDER_NAME));
                return realTemplatePath;
            }
            this.$errors.failWithoutHelp("Unable to find the template in temp directory. " +
                `Please open an issue at https://github.com/NativeScript/nativescript-cli/issues and send the output of the same command executed with --log trace.`);
        }).future()();
    }
    prepareNativeScriptTemplate(templateName, version, projectDir) {
        this.$logger.trace(`Using NativeScript verified template: ${templateName} with version ${version}.`);
        return this.$npmInstallationManager.install(templateName, projectDir, { version: version, dependencyType: "save" });
    }
}
exports.ProjectTemplatesService = ProjectTemplatesService;
$injector.register("projectTemplatesService", ProjectTemplatesService);
