"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("fs/promises");
const path_1 = require("path");
const chalk_1 = __importDefault(require("chalk"));
const constants_1 = require("../../constants");
const constants_2 = require("@mablhq-internal/runtime/core/constants");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const MobileAppFileCache_1 = require("@mablhq-internal/runtime/util/MobileAppFileCache");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
exports.command = `download <${constants_2.CommandArgId}> <${constants_1.CommandArgDestination}>`;
exports.describe = 'Download a mobile build file.';
exports.builder = (yargs) => {
    yargs
        .positional(constants_2.CommandArgId, {
        describe: 'ID of the mobile build file',
        type: 'string',
    })
        .positional(constants_1.CommandArgDestination, {
        describe: 'Relative path to destination directory or file',
        type: 'string',
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(downloadMobileAppFile);
async function downloadMobileAppFile(parsed) {
    try {
        const id = parsed[constants_2.CommandArgId];
        const destination = parsed[constants_1.CommandArgDestination];
        const mobileAppFile = await new MobileAppFileCache_1.MobileAppFileCache().getMobileAppFile(id);
        const downloadPath = await resolveDestination(destination, mobileAppFile);
        await (0, promises_1.copyFile)(mobileAppFile.path, downloadPath);
        loggingProvider_1.logger.info(chalk_1.default.green(`Mobile build file downloaded to ${downloadPath}`));
    }
    catch (error) {
        throw new Error(`Error downloading mobile build file: ${error}`);
    }
}
async function resolveDestination(destination, mobileAppFile) {
    let path = destination;
    try {
        if ((await (0, promises_1.stat)(destination)).isDirectory()) {
            path = (0, path_1.join)(destination, mobileAppFile.name);
        }
    }
    catch (error) {
    }
    return (0, path_1.resolve)(path);
}
