"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) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const constants = require("../constants");
const path = require("path");
const prepare_platform_service_1 = require("./prepare-platform-service");
const decorators_1 = require("../common/decorators");
class PreparePlatformNativeService extends prepare_platform_service_1.PreparePlatformService {
    constructor($fs, $xmlValidator, $hooksService, $nodeModulesBuilder, $pluginsService, $projectChangesService, $androidResourcesMigrationService) {
        super($fs, $hooksService, $xmlValidator);
        this.$nodeModulesBuilder = $nodeModulesBuilder;
        this.$pluginsService = $pluginsService;
        this.$projectChangesService = $projectChangesService;
        this.$androidResourcesMigrationService = $androidResourcesMigrationService;
    }
    addPlatform(info) {
        return __awaiter(this, void 0, void 0, function* () {
            yield info.platformData.platformProjectService.createProject(path.resolve(info.frameworkDir), info.installedVersion, info.projectData, info.config);
            info.platformData.platformProjectService.ensureConfigurationFileInAppResources(info.projectData);
            yield info.platformData.platformProjectService.interpolateData(info.projectData, info.config);
            info.platformData.platformProjectService.afterCreateProject(info.platformData.projectRoot, info.projectData);
            this.$projectChangesService.setNativePlatformStatus(info.platformData.normalizedPlatformName, info.projectData, { nativePlatformStatus: "2" });
        });
    }
    preparePlatform(config) {
        return __awaiter(this, void 0, void 0, function* () {
            if (config.changesInfo.hasChanges) {
                yield this.cleanProject(config.platform, config.appFilesUpdaterOptions, config.platformData, config.projectData);
            }
            if (!config.changesInfo || config.changesInfo.changesRequirePrepare || config.appFilesUpdaterOptions.bundle) {
                this.prepareAppResources(config.platformData, config.projectData);
            }
            if (!config.changesInfo || config.changesInfo.changesRequirePrepare) {
                yield config.platformData.platformProjectService.prepareProject(config.projectData, config.platformSpecificData);
            }
            const shouldPrepareModules = !config.changesInfo || config.changesInfo.modulesChanged;
            if (shouldPrepareModules) {
                yield this.$pluginsService.validate(config.platformData, config.projectData);
                const appDestinationDirectoryPath = path.join(config.platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
                const lastModifiedTime = this.$fs.exists(appDestinationDirectoryPath) ? this.$fs.getFsStats(appDestinationDirectoryPath).mtime : null;
                const tnsModulesDestinationPath = path.join(appDestinationDirectoryPath, constants.TNS_MODULES_FOLDER_NAME);
                const nodeModulesData = {
                    absoluteOutputPath: tnsModulesDestinationPath,
                    appFilesUpdaterOptions: config.appFilesUpdaterOptions,
                    lastModifiedTime,
                    platform: config.platform,
                    projectData: config.projectData,
                    projectFilesConfig: config.projectFilesConfig
                };
                yield this.$nodeModulesBuilder.prepareNodeModules({ nodeModulesData, release: config.appFilesUpdaterOptions.release });
            }
            if (!config.changesInfo || config.changesInfo.configChanged || config.changesInfo.modulesChanged) {
                yield config.platformData.platformProjectService.processConfigurationFilesFromAppResources(config.projectData, { release: config.appFilesUpdaterOptions.release, installPods: !shouldPrepareModules });
            }
            config.platformData.platformProjectService.interpolateConfigurationFile(config.projectData, config.platformSpecificData);
            this.$projectChangesService.setNativePlatformStatus(config.platform, config.projectData, { nativePlatformStatus: "3" });
        });
    }
    prepareAppResources(platformData, projectData) {
        const appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
        const appResourcesDestinationDirectoryPath = path.join(appDestinationDirectoryPath, constants.APP_RESOURCES_FOLDER_NAME);
        if (this.$fs.exists(appResourcesDestinationDirectoryPath)) {
            platformData.platformProjectService.prepareAppResources(appResourcesDestinationDirectoryPath, projectData);
            const appResourcesDestination = platformData.platformProjectService.getAppResourcesDestinationDirectoryPath(projectData);
            this.$fs.ensureDirectoryExists(appResourcesDestination);
            if (platformData.normalizedPlatformName.toLowerCase() === "android") {
                const appResourcesDirectoryPath = projectData.getAppResourcesDirectoryPath();
                const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated(appResourcesDirectoryPath);
                const appResourcesAndroid = path.join(appResourcesDirectoryPath, platformData.normalizedPlatformName);
                if (appResourcesDirStructureHasMigrated) {
                    this.$fs.copyFile(path.join(appResourcesAndroid, "src", "*"), appResourcesDestination);
                    this.$fs.deleteDirectory(appResourcesDestinationDirectoryPath);
                    return;
                }
                this.$fs.copyFile(path.join(appResourcesDestinationDirectoryPath, platformData.normalizedPlatformName, "*"), appResourcesDestination);
                this.$fs.deleteDirectory(path.join(appResourcesDestination, "libs"));
                this.$fs.deleteDirectory(appResourcesDestinationDirectoryPath);
                return;
            }
            this.$fs.copyFile(path.join(appResourcesDestinationDirectoryPath, platformData.normalizedPlatformName, "*"), appResourcesDestination);
            this.$fs.deleteDirectory(appResourcesDestinationDirectoryPath);
        }
    }
    cleanProject(platform, appFilesUpdaterOptions, platformData, projectData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (platform.toLowerCase() !== "android") {
                return;
            }
            const previousPrepareInfo = this.$projectChangesService.getPrepareInfo(platform, projectData);
            if (!previousPrepareInfo || previousPrepareInfo.nativePlatformStatus !== "3") {
                return;
            }
            const { release: previousWasRelease, bundle: previousWasBundle } = previousPrepareInfo;
            const { release: currentIsRelease, bundle: currentIsBundle } = appFilesUpdaterOptions;
            if ((previousWasRelease !== currentIsRelease) || (previousWasBundle !== currentIsBundle)) {
                yield platformData.platformProjectService.cleanProject(platformData.projectRoot, projectData);
            }
        });
    }
}
__decorate([
    decorators_1.performanceLog()
], PreparePlatformNativeService.prototype, "addPlatform", null);
__decorate([
    decorators_1.performanceLog()
], PreparePlatformNativeService.prototype, "preparePlatform", null);
exports.PreparePlatformNativeService = PreparePlatformNativeService;
$injector.register("preparePlatformNativeService", PreparePlatformNativeService);
