"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AndroidBundleToolService = void 0;
const path_1 = require("path");
const _ = require("lodash");
const helpers_1 = require("../../common/helpers");
const yok_1 = require("../../common/yok");
class AndroidBundleToolService {
    constructor($childProcess, $sysInfo, $errors) {
        this.$childProcess = $childProcess;
        this.$sysInfo = $sysInfo;
        this.$errors = $errors;
        this.aabToolPath = (0, path_1.resolve)((0, path_1.join)(__dirname, "../../../vendor/aab-tool/bundletool.jar"));
    }
    async buildApks(options) {
        if (!(0, helpers_1.hasValidAndroidSigning)(options.signingData)) {
            this.$errors.fail(`Unable to build "apks" without a full signing information.`);
        }
        const aabToolResult = await this.execBundleTool([
            "build-apks",
            "--bundle",
            options.aabFilePath,
            "--output",
            options.apksOutputPath,
            "--ks",
            options.signingData.keyStorePath,
            "--ks-pass",
            `pass:${options.signingData.keyStorePassword}`,
            "--ks-key-alias",
            options.signingData.keyStoreAlias,
            "--key-pass",
            `pass:${options.signingData.keyStoreAliasPassword}`,
        ]);
        if (aabToolResult.exitCode !== 0 && aabToolResult.stderr) {
            this.$errors.fail(`Unable to build "apks" from the provided "aab". Error: ${aabToolResult.stderr}`);
        }
    }
    async installApks(options) {
        const aabToolResult = await this.execBundleTool([
            "install-apks",
            "--apks",
            options.apksFilePath,
            "--device-id",
            options.deviceId,
        ]);
        if (aabToolResult.exitCode !== 0 && aabToolResult.stderr) {
            this.$errors.fail(`Unable to install "apks" on device "${options.deviceId}". Error: ${aabToolResult.stderr}`);
        }
    }
    async execBundleTool(args) {
        const javaPath = await this.getJavaPath();
        const defaultArgs = ["-jar", this.aabToolPath];
        const result = await this.$childProcess.trySpawnFromCloseEvent(javaPath, _.concat(defaultArgs, args));
        return result;
    }
    async getJavaPath() {
        if (!this.javaPath) {
            this.javaPath = await this.$sysInfo.getJavaPath();
        }
        return this.javaPath;
    }
}
exports.AndroidBundleToolService = AndroidBundleToolService;
yok_1.injector.register("androidBundleToolService", AndroidBundleToolService);
