"use strict";
var path = require("path");
var temp = require("temp");
var constants = require("../constants");
temp.track();
var ProjectTemplatesService = (function () {
    function ProjectTemplatesService($errors, $fs, $logger, $npm, $npmInstallationManager) {
        this.$errors = $errors;
        this.$fs = $fs;
        this.$logger = $logger;
        this.$npm = $npm;
        this.$npmInstallationManager = $npmInstallationManager;
    }
    ProjectTemplatesService.prototype.prepareTemplate = function (originalTemplateName, projectDir) {
        var _this = this;
        return (function () {
            var realTemplatePath;
            if (originalTemplateName) {
                var templateName = originalTemplateName.toLowerCase();
                var _a = templateName.split("@"), name_1 = _a[0], version = _a[1];
                if (constants.RESERVED_TEMPLATE_NAMES[name_1]) {
                    realTemplatePath = _this.prepareNativeScriptTemplate(constants.RESERVED_TEMPLATE_NAMES[name_1], version, projectDir).wait();
                }
                else {
                    realTemplatePath = _this.prepareNativeScriptTemplate(originalTemplateName, 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)).wait();
                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()();
    };
    ProjectTemplatesService.prototype.prepareNativeScriptTemplate = function (templateName, version, projectDir) {
        this.$logger.trace("Using NativeScript verified template: " + templateName + " with version " + version + ".");
        return this.$npmInstallationManager.install(templateName, projectDir, { version: version, dependencyType: "save" });
    };
    return ProjectTemplatesService;
}());
exports.ProjectTemplatesService = ProjectTemplatesService;
$injector.register("projectTemplatesService", ProjectTemplatesService);
