import { TransportStatusError, UnexpectedBootloader, StatusCodes } from "@ledgerhq/errors";
import Transport from "@ledgerhq/hw-transport";

/**
 * Attempt to fetch the size of the custom image set on the device,
 * or zero if there is no custom image set.
 */
export default async (transport: Transport): Promise<number> => {
  const res = await transport.send(0xe0, 0x64, 0x00, 0x00, Buffer.from([]), [
    StatusCodes.OK,
    StatusCodes.DEVICE_IN_RECOVERY_MODE,
    StatusCodes.UNKNOWN_APDU,
  ]);

  const status = res.readUInt16BE(res.length - 2);

  switch (status) {
    case StatusCodes.OK:
      return res.readUInt32BE();
    case StatusCodes.UNKNOWN_APDU: // Nb For il fw, since it doesn't support CLS
    case StatusCodes.CUSTOM_IMAGE_EMPTY:
      return 0;
    case StatusCodes.DEVICE_IN_RECOVERY_MODE:
      throw new UnexpectedBootloader();
  }
  throw new TransportStatusError(status);
};
