"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBatteryStatusTask = void 0;
const errors_1 = require("@ledgerhq/errors");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const core_1 = require("./core");
const quitApp_1 = require("../commands/quitApp");
const core_2 = require("../transports/core");
const getBatteryStatus_1 = __importDefault(require("../commands/getBatteryStatus"));
function internalGetBatteryStatusesTask({ deviceId, deviceName, statuses, }) {
    return new rxjs_1.Observable(subscriber => {
        return (0, core_2.withTransport)(deviceId, deviceName ? { matchDeviceByName: deviceName } : undefined)(({ transportRef }) => (0, quitApp_1.quitApp)(transportRef.current).pipe((0, operators_1.switchMap)(() => {
            const statusesObservable = statuses.map(statusType => (0, core_1.retryOnErrorsCommandWrapper)({
                command: ({ transport }) => (0, getBatteryStatus_1.default)({ transport, statusType }).pipe((0, operators_1.filter)((e) => e.type === "data")),
                allowedErrors: [{ maxRetries: 3, errorClass: errors_1.DisconnectedDevice }],
            })(transportRef, {}));
            // Runs sequentially the wanted status queries. Waits that the current observable completes.
            return (0, rxjs_1.concat)(...statusesObservable);
        }), (0, operators_1.map)(value => {
            const { batteryStatus } = value;
            return { type: "data", batteryStatus };
        }), (0, operators_1.catchError)((err) => {
            if (err instanceof errors_1.TransportStatusError && err.statusCode === errors_1.StatusCodes.UNKNOWN_APDU)
                return (0, rxjs_1.of)({ type: "taskError", error: "UnknownApdu" });
            return (0, rxjs_1.throwError)(() => err);
        }))).subscribe(subscriber);
    });
}
exports.getBatteryStatusTask = (0, core_1.sharedLogicTaskWrapper)(internalGetBatteryStatusesTask);
//# sourceMappingURL=getBatteryStatuses.js.map