"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, $options, 
    // private $pacoteService: IPacoteService,
    // private $projectDataService: IProjectDataService,
    $packageManager, $terminalSpinnerService, $analyticsService // private $tempService: ITempService
    ) {
        this.$fs = $fs;
        this.$logger = $logger;
        this.$options = $options;
        this.$packageManager = $packageManager;
        this.$terminalSpinnerService = $terminalSpinnerService;
        this.$analyticsService = $analyticsService;
    }
    addProjectHost() {
        return __awaiter(this, void 0, void 0, function* () { });
    }
    addPlatformSafe(projectData, platformData, packageToInstall, addPlatformData) {
        return __awaiter(this, void 0, void 0, function* () {
            const spinner = this.$terminalSpinnerService.createSpinner();
            try {
                spinner.start();
                // const frameworkDirPath = addPlatformData.frameworkPath ?
                // 	await this.extractPackage(packageToInstall)
                // 	: await this.installPackage(projectData.projectDir, packageToInstall);
                const frameworkDirPath = yield this.installPackage(projectData.projectDir, packageToInstall);
                const frameworkPackageJsonContent = this.$fs.readJson(path.join(frameworkDirPath, "..", "package.json"));
                const frameworkVersion = frameworkPackageJsonContent.version;
                // await this.setPlatformVersion(platformData, projectData, frameworkVersion);
                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}`);
        });
    }
    // private async extractPackage(pkg: string): Promise<string> {
    // 	const downloadedPackagePath = await this.$tempService.mkdirSync(
    // 		"runtimeDir"
    // 	);
    // 	await this.$pacoteService.extractPackage(pkg, downloadedPackagePath);
    // 	const frameworkDir = path.join(
    // 		downloadedPackagePath,
    // 		PROJECT_FRAMEWORK_FOLDER_NAME
    // 	);
    // 	return path.resolve(frameworkDir);
    // }
    installPackage(projectDir, packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            const frameworkDir = this.resolveFrameworkDir(projectDir, packageName);
            if (frameworkDir && this.$fs.exists(frameworkDir)) {
                // don't install if it's already installed
                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 {
            // strip version info if present <package>@1.2.3-rc.0 -> <package>
            // tested cases:
            // @nativescript/ios
            // @nativescript/ios@1
            // @nativescript/ios@1.2
            // @nativescript/ios@1.2.3
            // @nativescript/ios@1.2.3-
            // @nativescript/ios@1.2.3-rc
            // @nativescript/ios@1.2.3-rc.
            // @nativescript/ios@1.2.3-rc.0
            // @nativescript/ios@rc
            // @nativescript/ios@^7.0.0
            // @nativescript/ios@~7.0.0
            // tns-ios
            // tns-ios@1
            // tns-ios@1.2
            // tns-ios@1.2.3
            // tns-ios@1.2.3-
            // tns-ios@1.2.3-rc
            // tns-ios@1.2.3-rc.
            // tns-ios@1.2.3-rc.0
            // tns-ios@rc
            // tns-ios@^7.0.0
            // tns-ios@~7.0.0
            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;
    }
    addNativePlatform(platformData, projectData, frameworkDirPath, frameworkVersion) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            // here we should use ios OR android
            const platformDir = (_a = this.$options.hostProjectPath) !== null && _a !== void 0 ? _a : path.join(projectData.platformsDir, platformData.normalizedPlatformName.toLowerCase());
            this.$fs.deleteDirectory(platformDir);
            //if iosHost - dont create project
            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" /* TrackActionNames.AddPlatform */,
                additionalData: `${platformData.platformNameLowerCase}${constants_1.AnalyticsEventLabelDelimiter}${frameworkVersion}`,
            });
        });
    }
}
__decorate([
    (0, decorators_1.performanceLog)()
], AddPlatformService.prototype, "addNativePlatform", null);
exports.AddPlatformService = AddPlatformService;
yok_1.injector.register("addPlatformService", AddPlatformService);
//# sourceMappingURL=add-platform-service.js.map