"use strict";
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.XcodebuildArgsService = void 0;
const path = require("path");
const constants = require("../../constants");
const constants_1 = require("../../common/constants");
const yok_1 = require("../../common/yok");
const _ = require("lodash");
const ios_project_service_1 = require("../ios-project-service");
class XcodebuildArgsService {
    constructor($devicePlatformsConstants, $devicesService, $fs, $iOSWatchAppService, $logger) {
        this.$devicePlatformsConstants = $devicePlatformsConstants;
        this.$devicesService = $devicesService;
        this.$fs = $fs;
        this.$iOSWatchAppService = $iOSWatchAppService;
        this.$logger = $logger;
    }
    getBuildForSimulatorArgs(platformData, projectData, buildConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            let args = yield this.getArchitecturesArgs(buildConfig);
            if (this.$iOSWatchAppService.hasWatchApp(platformData, projectData)) {
                args = args.concat(["CODE_SIGNING_ALLOWED=NO"]);
            }
            else {
                args = args.concat(["CODE_SIGN_IDENTITY="]);
            }
            let destination = "generic/platform=iOS Simulator";
            let isvisionOS = this.$devicePlatformsConstants.isvisionOS(buildConfig.platform);
            if (isvisionOS) {
                destination = "platform=visionOS Simulator";
                if (buildConfig._device) {
                    destination += `,id=${buildConfig._device.deviceInfo.identifier}`;
                }
            }
            args = args
                .concat([
                "-destination",
                destination,
                "build",
                "-configuration",
                buildConfig.release ? constants_1.Configurations.Release : constants_1.Configurations.Debug,
            ])
                .concat(this.getBuildCommonArgs(platformData, projectData, isvisionOS ? ios_project_service_1.VisionSimulatorPlatformSdkName : ios_project_service_1.SimulatorPlatformSdkName))
                .concat(this.getBuildLoggingArgs())
                .concat(this.getXcodeProjectArgs(platformData.projectRoot, projectData));
            return args;
        });
    }
    getBuildForDeviceArgs(platformData, projectData, buildConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            const architectures = yield this.getArchitecturesArgs(buildConfig);
            const archivePath = path.join(platformData.getBuildOutputPath(buildConfig), projectData.projectName + ".xcarchive");
            const args = [
                "-destination",
                "generic/platform=iOS",
                "archive",
                "-archivePath",
                archivePath,
                "-configuration",
                buildConfig.release ? constants_1.Configurations.Release : constants_1.Configurations.Debug,
                "-allowProvisioningUpdates",
            ]
                .concat(this.getXcodeProjectArgs(platformData.projectRoot, projectData))
                .concat(architectures)
                .concat(this.getBuildCommonArgs(platformData, projectData, ios_project_service_1.DevicePlatformSdkName))
                .concat(this.getBuildLoggingArgs());
            return args;
        });
    }
    getArchitecturesArgs(buildConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            const args = [];
            if (this.$devicePlatformsConstants.isvisionOS(buildConfig.platform)) {
                args.push("ONLY_ACTIVE_ARCH=YES");
                return args;
            }
            const devicesArchitectures = buildConfig.buildForDevice
                ? yield this.getArchitecturesFromConnectedDevices(buildConfig)
                : [];
            if (!buildConfig.buildForDevice || devicesArchitectures.length > 1) {
                args.push("ONLY_ACTIVE_ARCH=NO");
            }
            return args;
        });
    }
    getXcodeProjectArgs(projectRoot, projectData) {
        const xcworkspacePath = path.join(projectRoot, `${projectData.projectName}.xcworkspace`);
        if (this.$fs.exists(xcworkspacePath)) {
            return [
                "-workspace",
                xcworkspacePath,
                "-scheme",
                projectData.projectName,
            ];
        }
        const xcodeprojPath = path.join(projectRoot, `${projectData.projectName}.xcodeproj`);
        return ["-project", xcodeprojPath, "-scheme", projectData.projectName];
    }
    getBuildLoggingArgs() {
        return this.$logger.getLevel() === "INFO" ? ["-quiet"] : [];
    }
    getBuildCommonArgs(platformData, projectData, platformSdkName) {
        let args = [];
        if (!this.$iOSWatchAppService.hasWatchApp(platformData, projectData)) {
            args = args.concat(["-sdk", platformSdkName]);
        }
        args = args.concat([
            "BUILD_DIR=" + path.join(platformData.projectRoot, constants.BUILD_DIR),
            "SHARED_PRECOMPS_DIR=" +
                path.join(platformData.projectRoot, constants.BUILD_DIR, "sharedpch"),
        ]);
        return args;
    }
    getArchitecturesFromConnectedDevices(buildConfig) {
        return __awaiter(this, void 0, void 0, function* () {
            const platform = this.$devicePlatformsConstants.iOS.toLowerCase();
            yield this.$devicesService.initialize({
                platform,
                deviceId: buildConfig.device,
                skipEmulatorStart: true,
            });
            const instances = this.$devicesService.getDevicesForPlatform(platform);
            const architectures = _(instances)
                .map((d) => d.deviceInfo.activeArchitecture)
                .filter((d) => !!d)
                .uniq()
                .value();
            return architectures;
        });
    }
}
exports.XcodebuildArgsService = XcodebuildArgsService;
yok_1.injector.register("xcodebuildArgsService", XcodebuildArgsService);
