"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"));
const errors_2 = require("../errors");
/**
 * Clear an existing custom image from the device, we could argue this would need to be
 * a task and a command, separated, but we are not quite there yet so I'm leaving them in
 * the same file. Not totally convinced but here we are.
 */
const command = async (transport) => {
    const res = await transport.send(0xe0, 0x63, 0x00, 0x00, Buffer.from([]), [
        errors_1.StatusCodes.OK,
        errors_1.StatusCodes.DEVICE_IN_RECOVERY_MODE,
        errors_1.StatusCodes.USER_REFUSED_ON_DEVICE,
        errors_1.StatusCodes.CUSTOM_IMAGE_EMPTY,
        errors_1.StatusCodes.UNKNOWN_APDU,
    ]);
    const status = res.readUInt16BE(res.length - 2);
    switch (status) {
        case errors_1.StatusCodes.OK:
            return;
        case errors_1.StatusCodes.CUSTOM_IMAGE_EMPTY:
            throw new errors_2.ImageDoesNotExistOnDevice();
        case errors_1.StatusCodes.DEVICE_IN_RECOVERY_MODE:
            throw new errors_1.UnexpectedBootloader();
        case errors_1.StatusCodes.USER_REFUSED_ON_DEVICE:
            throw new errors_1.UserRefusedOnDevice();
    }
    throw new errors_1.TransportStatusError(status);
};
exports.command = command;
function removeImage({ deviceId }) {
    return (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: "removeImagePermissionRequested" });
            await (0, exports.command)(transport);
            subscriber.next({ type: "imageRemoved" });
            subscriber.complete();
        }), (0, operators_1.catchError)(e => {
            subscriber.error(e);
            return (0, rxjs_1.throwError)(() => e);
        }))
            .subscribe();
        return () => {
            timeoutSub.unsubscribe();
            sub.unsubscribe();
        };
    }));
}
exports.default = removeImage;
//# sourceMappingURL=customLockScreenRemove.js.map