"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.AddPlatformService = void 0;
const path = require("path");
const constants_1 = require("../../constants");
const decorators_1 = require("../../common/decorators");
const yok_1 = require("../../common/yok");
class AddPlatformService {
    constructor($fs, $logger, $options, $packageManager, $terminalSpinnerService, $analyticsService) {
        this.$fs = $fs;
        this.$logger = $logger;
        this.$options = $options;
        this.$packageManager = $packageManager;
        this.$terminalSpinnerService = $terminalSpinnerService;
        this.$analyticsService = $analyticsService;
    }
    async addProjectHost() { }
    async addPlatformSafe(projectData, platformData, packageToInstall, addPlatformData) {
        const spinner = this.$terminalSpinnerService.createSpinner();
        try {
            spinner.start();
            const frameworkDirPath = await this.installPackage(projectData.projectDir, packageToInstall);
            const frameworkPackageJsonContent = this.$fs.readJson(path.join(frameworkDirPath, "..", "package.json"));
            const frameworkVersion = frameworkPackageJsonContent.version;
            await this.trackPlatformVersion(frameworkVersion, platformData);
            if (!addPlatformData.nativePrepare ||
                !addPlatformData.nativePrepare.skipNativePrepare) {
                await this.addNativePlatform(platformData, projectData, frameworkDirPath, frameworkVersion);
            }
            return frameworkVersion;
        }
        catch (err) {
            const platformPath = path.join(projectData.platformsDir, platformData.platformNameLowerCase);
            this.$fs.deleteDirectory(platformPath);
            throw err;
        }
        finally {
            spinner.stop();
        }
    }
    async setPlatformVersion(platformData, projectData, frameworkVersion) {
        await this.installPackage(projectData.projectDir, `${platformData.frameworkPackageName}@${frameworkVersion}`);
    }
    async installPackage(projectDir, packageName) {
        const frameworkDir = this.resolveFrameworkDir(projectDir, packageName);
        if (frameworkDir && this.$fs.exists(frameworkDir)) {
            return frameworkDir;
        }
        const installedPackage = await this.$packageManager.install(packageName, projectDir, {
            silent: true,
            dev: true,
            "save-dev": true,
            "save-exact": true,
        });
        if (!installedPackage.name) {
            return "";
        }
        return this.resolveFrameworkDir(projectDir, installedPackage.name) || "";
    }
    resolveFrameworkDir(projectDir, packageName) {
        try {
            packageName = packageName.replace(/(.+)@.+$/g, "$1");
            const frameworkDir = require
                .resolve(`${packageName}/package.json`, {
                paths: [projectDir],
            })
                .replace("package.json", constants_1.PROJECT_FRAMEWORK_FOLDER_NAME);
            if (frameworkDir) {
                return path.resolve(frameworkDir);
            }
        }
        catch (err) {
            this.$logger.trace(`Couldn't resolve installed framework. Continuing with install...`, err);
        }
        return null;
    }
    async addNativePlatform(platformData, projectData, frameworkDirPath, frameworkVersion) {
        var _a;
        const platformDir = (_a = this.$options.hostProjectPath) !== null && _a !== void 0 ? _a : path.join(projectData.platformsDir, platformData.normalizedPlatformName.toLowerCase());
        this.$fs.deleteDirectory(platformDir);
        await platformData.platformProjectService.createProject(path.resolve(frameworkDirPath), frameworkVersion, projectData);
        platformData.platformProjectService.ensureConfigurationFileInAppResources(projectData);
        await platformData.platformProjectService.interpolateData(projectData);
        platformData.platformProjectService.afterCreateProject(platformData.projectRoot, projectData);
    }
    async trackPlatformVersion(frameworkVersion, platformData) {
        await this.$analyticsService.trackEventActionInGoogleAnalytics({
            action: "Add Platform",
            additionalData: `${platformData.platformNameLowerCase}${constants_1.AnalyticsEventLabelDelimiter}${frameworkVersion}`,
        });
    }
}
exports.AddPlatformService = AddPlatformService;
__decorate([
    (0, decorators_1.performanceLog)()
], AddPlatformService.prototype, "addNativePlatform", null);
yok_1.injector.register("addPlatformService", AddPlatformService);
