"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.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, $packageManager, $terminalSpinnerService, $analyticsService) {
        this.$fs = $fs;
        this.$logger = $logger;
        this.$packageManager = $packageManager;
        this.$terminalSpinnerService = $terminalSpinnerService;
        this.$analyticsService = $analyticsService;
    }
    addPlatformSafe(projectData, platformData, packageToInstall, addPlatformData) {
        return __awaiter(this, void 0, void 0, function* () {
            const spinner = this.$terminalSpinnerService.createSpinner();
            try {
                spinner.start();
                const frameworkDirPath = yield this.installPackage(projectData.projectDir, packageToInstall);
                const frameworkPackageJsonContent = this.$fs.readJson(path.join(frameworkDirPath, "..", "package.json"));
                const frameworkVersion = frameworkPackageJsonContent.version;
                yield this.trackPlatformVersion(frameworkVersion, platformData);
                if (!addPlatformData.nativePrepare ||
                    !addPlatformData.nativePrepare.skipNativePrepare) {
                    yield 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();
            }
        });
    }
    setPlatformVersion(platformData, projectData, frameworkVersion) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.installPackage(projectData.projectDir, `${platformData.frameworkPackageName}@${frameworkVersion}`);
        });
    }
    installPackage(projectDir, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            const frameworkDir = this.resolveFrameworkDir(projectDir, packageName);
            if (frameworkDir && this.$fs.exists(frameworkDir)) {
                return frameworkDir;
            }
            const installedPackage = yield 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(/@[\d.]+$/g, "");
            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...`);
        }
        return null;
    }
    addNativePlatform(platformData, projectData, frameworkDirPath, frameworkVersion) {
        return __awaiter(this, void 0, void 0, function* () {
            const platformDir = path.join(projectData.platformsDir, platformData.normalizedPlatformName.toLowerCase());
            this.$fs.deleteDirectory(platformDir);
            yield platformData.platformProjectService.createProject(path.resolve(frameworkDirPath), frameworkVersion, projectData);
            platformData.platformProjectService.ensureConfigurationFileInAppResources(projectData);
            yield platformData.platformProjectService.interpolateData(projectData);
            platformData.platformProjectService.afterCreateProject(platformData.projectRoot, projectData);
        });
    }
    trackPlatformVersion(frameworkVersion, platformData) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.$analyticsService.trackEventActionInGoogleAnalytics({
                action: "Add Platform",
                additionalData: `${platformData.platformNameLowerCase}${constants_1.AnalyticsEventLabelDelimiter}${frameworkVersion}`,
            });
        });
    }
}
__decorate([
    decorators_1.performanceLog()
], AddPlatformService.prototype, "addNativePlatform", null);
exports.AddPlatformService = AddPlatformService;
yok_1.injector.register("addPlatformService", AddPlatformService);
