"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const promises_1 = require("node:fs/promises");
const path_1 = require("path");
const chalk_1 = __importDefault(require("chalk"));
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const util_1 = require("../../commandUtil/util");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const constants_2 = require("../../constants");
const upload_1 = require("@mablhq-internal/runtime/upload");
const env_1 = require("@mablhq-internal/runtime/env/env");
exports.command = [
    `upload <${constants_2.CommandArgMobileBuildFilePath}>`,
    `create <${constants_2.CommandArgMobileBuildFilePath}>`,
];
exports.describe = 'Upload a new mobile build file';
exports.builder = (yargs) => {
    yargs
        .positional(constants_2.CommandArgMobileBuildFilePath, {
        describe: 'Relative path to mobile build file file',
    })
        .option(constants_2.CommandArgBranch, {
        describe: 'Branch from which this mobile build file was built',
        type: 'string',
    })
        .option(constants_1.CommandArgLabels, {
        describe: 'Space delimited labels to save the file with',
        type: 'array',
    })
        .option(constants_2.CommandArgMobilePlatform, {
        describe: 'The mobile platform',
        defaultDescription: 'inferred from app binary extension',
        type: 'string',
        choices: [
            mablApi_1.MobilePlatformEnum.Android.toString().toLowerCase(),
            mablApi_1.MobilePlatformEnum.Ios.toString().toLowerCase(),
        ],
    })
        .version(false)
        .option(constants_2.CommandArgVersion, {
        describe: 'Version of this mobile build file',
        type: 'string',
    })
        .option(constants_1.CommandArgWorkspaceId, {
        alias: constants_2.CommandArgAliases.WorkspaceId,
        describe: `Workspace to create mobile build file in`,
        type: 'string',
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(createMobileAppFile);
async function createMobileAppFile(parsed) {
    const { branch, labels, platform, version } = parsed;
    const file = parsed[constants_2.CommandArgMobileBuildFilePath];
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    const mobileAppFilePrototype = {
        branch,
        labels,
        platform,
        version,
        workspace_id: workspaceId,
    };
    const { httpClient } = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const uploadClient = new upload_1.UploadClient({
        authorizationProvider: (0, upload_1.createAuthorizationProvider)(),
        httpClient,
        uploadServiceUrl: new URL(env_1.BASE_API_URL),
    });
    loggingProvider_1.logger.info(`Beginning upload of mobile app file ${(0, path_1.basename)((0, path_1.resolve)(file))} to ${workspaceId}`);
    const mobileAppFile = await uploadClient.uploadMobileAppFile(file, mobileAppFilePrototype, await createUploadProgressListener(file));
    loggingProvider_1.logger.info(chalk_1.default.green(`Created mobile app file ${chalk_1.default.bold(mobileAppFile.id)}`));
}
async function createUploadProgressListener(filePath) {
    const fileName = (0, path_1.basename)((0, path_1.resolve)(filePath));
    const { size } = await (0, promises_1.stat)(filePath);
    let totalBytesSent = 0;
    return ({ chunkSizeBytes }) => {
        totalBytesSent += chunkSizeBytes;
        const completedPercentage = Math.round((totalBytesSent / size) * 100.0);
        loggingProvider_1.logger.info(`Uploaded ${totalBytesSent}b of ${size}b (${completedPercentage}%) of mobile app file ${fileName}`);
    };
}
