"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;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
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 = {};
    }
    prepareTemplate(templateValue, projectDir) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!templateValue) {
                templateValue = constants.RESERVED_TEMPLATE_NAMES["default"];
            }
            const templateNameParts = yield this.$packageManager.getPackageNameParts(templateValue);
            templateValue =
                constants.RESERVED_TEMPLATE_NAMES[templateNameParts.name] ||
                    templateNameParts.name;
            const version = yield this.getDesiredVersion(templateValue, templateNameParts.version);
            const fullTemplateName = yield this.$packageManager.getPackageFullName({
                name: templateValue,
                version: version,
            });
            const templatePackageJsonContent = yield this.getTemplatePackageJsonContent(fullTemplateName);
            const templateNameToBeTracked = this.getTemplateNameToBeTracked(templateValue, templatePackageJsonContent);
            if (templateNameToBeTracked) {
                yield this.$analyticsService.trackEventActionInGoogleAnalytics({
                    action: "Create project",
                    isForDevice: null,
                    additionalData: templateNameToBeTracked,
                });
                yield this.$analyticsService.trackEventActionInGoogleAnalytics({
                    action: "Using Template",
                    additionalData: templateNameToBeTracked,
                });
            }
            return {
                templateName: templateValue,
                templatePackageJsonContent,
                version,
            };
        });
    }
    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];
        });
    }
    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}`);
        }
    }
    getDesiredVersion(templateName, defaultVersion) {
        return __awaiter(this, void 0, void 0, function* () {
            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);
            }
        });
    }
}
__decorate([
    (0, decorators_1.performanceLog)()
], ProjectTemplatesService.prototype, "prepareTemplate", null);
exports.ProjectTemplatesService = ProjectTemplatesService;
yok_1.injector.register("projectTemplatesService", ProjectTemplatesService);
