"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("@ledgerhq/errors");
const customLockScreenRemove_1 = __importStar(require("./customLockScreenRemove"));
const hw_transport_1 = __importDefault(require("@ledgerhq/hw-transport"));
const errors_2 = require("../errors");
const deviceAccess_1 = require("./deviceAccess");
const rxjs_1 = require("rxjs");
const getDeviceInfo_1 = __importDefault(require("./getDeviceInfo"));
jest.mock("./deviceAccess");
const mockedWithDevice = jest.mocked(deviceAccess_1.withDevice);
function mockWithDevice(transport) {
    mockedWithDevice.mockReturnValue(job => (0, rxjs_1.from)(job(transport)));
}
jest.mock("./getDeviceInfo");
const mockedGetDeviceInfo = jest.mocked(getDeviceInfo_1.default);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore next-line
const mockTransportGenerator = out => ({ send: () => out });
describe("customLockScreenRemove", () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });
    test("should succeed if user approves", async () => {
        const mockedTransport = mockTransportGenerator(Buffer.from(errors_1.StatusCodes.OK.toString(16), "hex"));
        await expect((0, customLockScreenRemove_1.command)(mockedTransport)).resolves.toBeUndefined();
    });
    test("should fail with correct error if user refuses", async () => {
        const mockedTransport = mockTransportGenerator(Buffer.from(errors_1.StatusCodes.USER_REFUSED_ON_DEVICE.toString(16), "hex"));
        await expect((0, customLockScreenRemove_1.command)(mockedTransport)).rejects.toThrow(errors_1.UserRefusedOnDevice);
    });
    test("should throw if user refuses", async () => {
        const mockedTransport = mockTransportGenerator(Buffer.from(errors_1.StatusCodes.USER_REFUSED_ON_DEVICE.toString(16), "hex"));
        await expect((0, customLockScreenRemove_1.command)(mockedTransport)).rejects.toThrow(Error);
    });
    test("missing image, should throw", async () => {
        const mockedTransport = mockTransportGenerator(Buffer.from(errors_1.StatusCodes.CUSTOM_IMAGE_EMPTY.toString(16), "hex"));
        await expect((0, customLockScreenRemove_1.command)(mockedTransport)).rejects.toThrow(errors_2.ImageDoesNotExistOnDevice);
    });
    test("unexpected bootloader or any other code, should throw", async () => {
        const mockedTransport = mockTransportGenerator(Buffer.from(errors_1.StatusCodes.DEVICE_IN_RECOVERY_MODE.toString(16), "hex"));
        await expect((0, customLockScreenRemove_1.command)(mockedTransport)).rejects.toThrow(errors_1.UnexpectedBootloader);
    });
});
describe("removeImage deviceAction", () => {
    beforeEach(() => {
        jest.clearAllMocks();
        mockWithDevice(new hw_transport_1.default());
    });
    it('should emit an "unresponsiveDevice" event if getDeviceInfo takes too long', done => {
        mockedGetDeviceInfo.mockImplementation(() => new Promise(() => { }));
        (0, customLockScreenRemove_1.default)({ deviceId: "deviceId", request: {} }).subscribe({
            next: event => {
                if (!event) {
                    done(new Error("unexpected undefined event"));
                }
                const { type } = event;
                if (type === "unresponsiveDevice") {
                    done();
                }
                else {
                    done(new Error("unexpected event"));
                }
            },
            error: err => {
                done(err); // it should not error
            },
        });
    });
    it("should error if getDeviceInfo fails", done => {
        mockedGetDeviceInfo.mockRejectedValue(new Error("failed"));
        (0, customLockScreenRemove_1.default)({ deviceId: "deviceId", request: {} }).subscribe({
            next: () => {
                done(new Error("unexpected event"));
            },
            error: err => {
                try {
                    expect(err).toMatchObject(new Error("failed"));
                    done();
                }
                catch (e) {
                    done(e);
                }
            },
        });
    });
    it("should complete with the correct events in case of success", done => {
        mockedGetDeviceInfo.mockResolvedValue({});
        mockWithDevice(mockTransportGenerator(Buffer.from(errors_1.StatusCodes.OK.toString(16), "hex")));
        const expectedEventTypes = ["removeImagePermissionRequested", "imageRemoved"];
        const observedEventTypes = [];
        (0, customLockScreenRemove_1.default)({ deviceId: "deviceId", request: {} }).subscribe({
            next: event => {
                if (!event) {
                    done(new Error("unexpected undefined event"));
                }
                const { type } = event;
                observedEventTypes.push(type);
            },
            complete: () => {
                try {
                    expect(observedEventTypes).toEqual(expectedEventTypes);
                    done();
                }
                catch (e) {
                    done(e);
                }
            },
            error: err => {
                done(err); // it should not error
            },
        });
    });
    it("should complete with the correct events in case of failure", done => {
        mockedGetDeviceInfo.mockResolvedValue({});
        mockWithDevice(mockTransportGenerator(Buffer.from(errors_1.StatusCodes.USER_REFUSED_ON_DEVICE.toString(16), "hex")));
        const expectedEventTypes = ["removeImagePermissionRequested"];
        const observedEventTypes = [];
        (0, customLockScreenRemove_1.default)({ deviceId: "deviceId", request: {} }).subscribe({
            next: event => {
                if (!event) {
                    done(new Error("unexpected undefined event"));
                }
                const { type } = event;
                observedEventTypes.push(type);
            },
            complete: () => {
                done(new Error("unexpected completion"));
            },
            error: err => {
                try {
                    expect(observedEventTypes).toEqual(expectedEventTypes);
                    expect(err).toMatchObject(new errors_1.UserRefusedOnDevice());
                    done();
                }
                catch (e) {
                    done(e); // it should not error
                }
            },
        });
    });
});
//# sourceMappingURL=customLockScreenRemove.test.js.map