import { DisconnectedDevice, StatusCodes, TransportStatusError } from "@ledgerhq/errors";
import { Observable, concat, of, throwError } from "rxjs";
import { catchError, filter, map, switchMap } from "rxjs/operators";
import { retryOnErrorsCommandWrapper, sharedLogicTaskWrapper } from "./core";
import { quitApp } from "../commands/quitApp";
import { withTransport } from "../transports/core";
import getBatteryStatus from "../commands/getBatteryStatus";
function internalGetBatteryStatusesTask({ deviceId, deviceName, statuses, }) {
    return new Observable(subscriber => {
        return withTransport(deviceId, deviceName ? { matchDeviceByName: deviceName } : undefined)(({ transportRef }) => quitApp(transportRef.current).pipe(switchMap(() => {
            const statusesObservable = statuses.map(statusType => retryOnErrorsCommandWrapper({
                command: ({ transport }) => getBatteryStatus({ transport, statusType }).pipe(filter((e) => e.type === "data")),
                allowedErrors: [{ maxRetries: 3, errorClass: DisconnectedDevice }],
            })(transportRef, {}));
            // Runs sequentially the wanted status queries. Waits that the current observable completes.
            return concat(...statusesObservable);
        }), map(value => {
            const { batteryStatus } = value;
            return { type: "data", batteryStatus };
        }), catchError((err) => {
            if (err instanceof TransportStatusError && err.statusCode === StatusCodes.UNKNOWN_APDU)
                return of({ type: "taskError", error: "UnknownApdu" });
            return throwError(() => err);
        }))).subscribe(subscriber);
    });
}
export const getBatteryStatusTask = sharedLogicTaskWrapper(internalGetBatteryStatusesTask);
//# sourceMappingURL=getBatteryStatuses.js.map