"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const temp = require("temp");
const constants = require("../constants");
const util_1 = require("util");
temp.track();
class ProjectTemplatesService {
    constructor($analyticsService, $fs, $logger, $npmInstallationManager, $pacoteService, $errors) {
        this.$analyticsService = $analyticsService;
        this.$fs = $fs;
        this.$logger = $logger;
        this.$npmInstallationManager = $npmInstallationManager;
        this.$pacoteService = $pacoteService;
        this.$errors = $errors;
        this.templatePackageContents = {};
    }
    prepareTemplate(originalTemplateName, projectDir) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!originalTemplateName) {
                originalTemplateName = constants.RESERVED_TEMPLATE_NAMES["default"];
            }
            const [name, version] = originalTemplateName.split("@");
            const templateName = constants.RESERVED_TEMPLATE_NAMES[name.toLowerCase()] || name;
            const fullTemplateName = version ? `${templateName}@${version}` : templateName;
            const templatePackageJsonContent = yield this.getTemplatePackageJsonContent(fullTemplateName);
            const templateVersion = yield this.getTemplateVersion(fullTemplateName);
            let templatePath = null;
            if (templateVersion === constants.TemplateVersions.v1) {
                templatePath = yield this.prepareNativeScriptTemplate(templateName, version, projectDir);
                this.$fs.deleteDirectory(path.join(templatePath, constants.NODE_MODULES_FOLDER_NAME));
            }
            yield this.$analyticsService.track("Template used for project creation", templateName);
            const templateNameToBeTracked = this.getTemplateNameToBeTracked(templateName, templatePackageJsonContent);
            if (templateNameToBeTracked) {
                yield this.$analyticsService.trackEventActionInGoogleAnalytics({
                    action: "Create project",
                    isForDevice: null,
                    additionalData: templateNameToBeTracked
                });
                yield this.$analyticsService.trackEventActionInGoogleAnalytics({
                    action: "Using Template",
                    additionalData: `${templateNameToBeTracked}${constants.AnalyticsEventLabelDelimiter}${templateVersion}`
                });
            }
            return { templateName, templatePath, templateVersion, templatePackageJsonContent };
        });
    }
    getTemplateVersion(templateName) {
        return __awaiter(this, void 0, void 0, function* () {
            const packageJsonContent = yield this.getTemplatePackageJsonContent(templateName);
            const templateVersionFromPackageJson = packageJsonContent && packageJsonContent.nativescript && packageJsonContent.nativescript.templateVersion;
            if (templateVersionFromPackageJson) {
                this.$logger.trace(`The template ${templateName} has version ${templateVersionFromPackageJson}.`);
                if (_.values(constants.TemplateVersions).indexOf(templateVersionFromPackageJson) === -1) {
                    this.$errors.failWithoutHelp(util_1.format(constants.ProjectTemplateErrors.InvalidTemplateVersionStringFormat, templateName, templateVersionFromPackageJson));
                }
                return templateVersionFromPackageJson;
            }
            return constants.TemplateVersions.v1;
        });
    }
    getTemplatePackageJsonContent(templateName) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.templatePackageContents[templateName]) {
                this.templatePackageContents[templateName] = yield this.$pacoteService.manifest(templateName, { fullMetadata: true });
            }
            return this.templatePackageContents[templateName];
        });
    }
    prepareNativeScriptTemplate(templateName, version, projectDir) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$logger.trace(`Using NativeScript verified template: ${templateName} with version ${version}.`);
            return this.$npmInstallationManager.install(templateName, projectDir, { version: version, dependencyType: "save" });
        });
    }
    getTemplateNameToBeTracked(templateName, packageJsonContent) {
        try {
            if (this.$fs.exists(templateName)) {
                const templateNameToBeTracked = (packageJsonContent && packageJsonContent.name) || path.basename(templateName);
                return `${constants.ANALYTICS_LOCAL_TEMPLATE_PREFIX}${templateNameToBeTracked}`;
            }
            return templateName;
        }
        catch (err) {
            this.$logger.trace(`Unable to get template name to be tracked, error is: ${err}`);
        }
    }
}
exports.ProjectTemplatesService = ProjectTemplatesService;
$injector.register("projectTemplatesService", ProjectTemplatesService);
