"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildIos = void 0;
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
const utils_1 = require("./utils");
const core_1 = require("@oclif/core");
const iosUtils_1 = require("./iosUtils");
const config_1 = require("./config");
const appName = (0, utils_1.getAppName)();
function installPods() {
    core_1.ux.debug('Pod install');
    const iosFolder = path_1.default.join((0, utils_1.getProjectRootDir)(), 'ios');
    (0, utils_1.executeCommand)('pod install', { cwd: iosFolder });
}
function _buildIos(buildType, platform = iosUtils_1.iosBuildPlatforms.simulator) {
    const iosFolder = path_1.default.join((0, utils_1.getProjectRootDir)(), 'ios');
    const workspacePath = path_1.default.join(iosFolder, `${appName}.xcworkspace`);
    const buildFlavor = (0, config_1.getIosFlavors)(buildType);
    if (!buildFlavor) {
        throw new Error(`No build flavor found for ${buildType}`);
    }
    const archivePath = `${iosFolder}/build/Products/${appName}.xcarchive`;
    const buildCommand = `RCT_NO_LAUNCH_PACKAGER=true xcodebuild \
      -workspace "${workspacePath}" \
      -scheme "${buildFlavor.scheme}" \
      -configuration ${buildFlavor.config} \
      -sdk ${platform.name} \
      ${platform.buildCmd}
    `;
    (0, utils_1.executeCommand)(buildCommand);
    if (platform.buildCmd === 'build') {
        // todo handle Debug/release
        const source = `${iosFolder}/DerivedData/${appName}/build/Products/Debug-${platform.name}/${appName}.${platform.ext}`;
        const { destinationDir, destination } = (0, iosUtils_1.getIosBuildDestination)(platform, buildFlavor.flavorDir);
        (0, utils_1.executeCommand)(`mkdir -p ${destinationDir}`);
        (0, utils_1.executeCommand)(`rm -rf ${destination}`);
        const copyCommand = `cp -a '${source}' '${destination}'`;
        console.log(`Copying: ${copyCommand}`);
        (0, utils_1.executeCommand)(copyCommand);
        return destination;
    }
    else {
        // archive
        // todo
        const generateIpaCommand = `xcodebuild -exportArchive \
      -archivePath '${archivePath}' \
      -exportPath "${iosFolder}/build/Products/IPA" \
      -exportOptionsPlist ${iosFolder}/${appName}/info.plist \
      -allowProvisioningUpdates
    `;
        (0, utils_1.executeCommand)(generateIpaCommand);
    }
}
function buildIos(buildType, platform = iosUtils_1.iosBuildPlatforms.simulator) {
    installPods();
    _buildIos(buildType, platform);
}
exports.buildIos = buildIos;
