"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProjectTemplatesService = void 0;
const path = require("path");
const semver = require("semver");
const constants = require("../constants");
const decorators_1 = require("../common/decorators");
const yok_1 = require("../common/yok");
class ProjectTemplatesService {
    constructor($analyticsService, $fs, $logger, $packageInstallationManager, $pacoteService, $packageManager, $staticConfig) {
        this.$analyticsService = $analyticsService;
        this.$fs = $fs;
        this.$logger = $logger;
        this.$packageInstallationManager = $packageInstallationManager;
        this.$pacoteService = $pacoteService;
        this.$packageManager = $packageManager;
        this.$staticConfig = $staticConfig;
        this.templatePackageContents = {};
    }
    async prepareTemplate(templateValue, projectDir) {
        if (!templateValue) {
            templateValue = constants.RESERVED_TEMPLATE_NAMES["default"];
        }
        const templateNameParts = await this.$packageManager.getPackageNameParts(templateValue);
        templateValue =
            constants.RESERVED_TEMPLATE_NAMES[templateNameParts.name] ||
                templateNameParts.name;
        const version = await this.getDesiredVersion(templateValue, templateNameParts.version);
        const fullTemplateName = await this.$packageManager.getPackageFullName({
            name: templateValue,
            version: version,
        });
        const templatePackageJsonContent = await this.getTemplatePackageJsonContent(fullTemplateName);
        const templateNameToBeTracked = this.getTemplateNameToBeTracked(templateValue, templatePackageJsonContent);
        if (templateNameToBeTracked) {
            await this.$analyticsService.trackEventActionInGoogleAnalytics({
                action: "Create project",
                isForDevice: null,
                additionalData: templateNameToBeTracked,
            });
            await this.$analyticsService.trackEventActionInGoogleAnalytics({
                action: "Using Template",
                additionalData: templateNameToBeTracked,
            });
        }
        return {
            templateName: templateValue,
            templatePackageJsonContent,
            version,
        };
    }
    async getTemplatePackageJsonContent(templateName) {
        if (!this.templatePackageContents[templateName]) {
            this.templatePackageContents[templateName] = await this.$pacoteService.manifest(templateName, {
                fullMetadata: true,
            });
        }
        return this.templatePackageContents[templateName];
    }
    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}`);
        }
    }
    async getDesiredVersion(templateName, defaultVersion) {
        if (defaultVersion) {
            return defaultVersion;
        }
        if (this.$fs.exists(templateName)) {
            return "";
        }
        try {
            const cliMajorVersion = semver.parse(semver.coerce(this.$staticConfig.version)).major;
            return `^${cliMajorVersion}.0.0`;
        }
        catch (err) {
            return this.$packageInstallationManager.getLatestCompatibleVersionSafe(templateName);
        }
    }
}
exports.ProjectTemplatesService = ProjectTemplatesService;
__decorate([
    (0, decorators_1.performanceLog)()
], ProjectTemplatesService.prototype, "prepareTemplate", null);
yok_1.injector.register("projectTemplatesService", ProjectTemplatesService);
