"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.command = void 0;
const errors_1 = require("@ledgerhq/errors");
const rxjs_1 = require("rxjs");
const deviceAccess_1 = require("./deviceAccess");
const operators_1 = require("rxjs/operators");
const getDeviceInfo_1 = __importDefault(require("./getDeviceInfo"));
/**
 * Prompt the user to uninstall all applications at once in order to avoid
 * having to iterate over the installed applications one by one. This avoid
 * unnnecesary HSM connections, speeds up the flow and improves the UX.
 */
const command = async (transport) => {
    const res = await transport.send(0xe0, 0x6dd, 0x00, 0x00, Buffer.from([]), [
        errors_1.StatusCodes.OK,
        errors_1.StatusCodes.UNKNOWN_APDU,
        errors_1.StatusCodes.USER_REFUSED_ON_DEVICE,
        errors_1.StatusCodes.UNKNOWN_APDU,
    ]);
    const status = res.readUInt16BE(res.length - 2);
    // We can complete with OK/KO, if the APDU is not available we can continue
    // with the legacy queue based HSM uninstall, if we succeed, we can clear
    // the queue.
    switch (status) {
        case errors_1.StatusCodes.OK:
            return true;
        case errors_1.StatusCodes.USER_REFUSED_ON_DEVICE:
            throw new errors_1.UserRefusedOnDevice();
        case errors_1.StatusCodes.UNKNOWN_APDU:
            return false;
    }
    throw new errors_1.TransportStatusError(status);
};
exports.command = command;
function uninstallAllApps({ deviceId }) {
    const sub = (0, deviceAccess_1.withDevice)(deviceId)(transport => new rxjs_1.Observable(subscriber => {
        const timeoutSub = (0, rxjs_1.of)({
            type: "unresponsiveDevice",
        })
            .pipe((0, operators_1.delay)(1000))
            .subscribe(e => subscriber.next(e));
        const sub = (0, rxjs_1.from)((0, getDeviceInfo_1.default)(transport))
            .pipe((0, operators_1.mergeMap)(async () => {
            timeoutSub.unsubscribe();
            subscriber.next({ type: "uninstallAllAppsPermissionRequested" });
            await (0, exports.command)(transport);
            subscriber.next({ type: "appsUninstalled" });
        }))
            .subscribe(subscriber);
        return () => {
            timeoutSub.unsubscribe();
            sub.unsubscribe();
        };
    }));
    return sub;
}
exports.default = uninstallAllApps;
//# sourceMappingURL=uninstallAllApps.js.map