'use strict';

const { readJpegWidth } = require('../src/cameraSwitch');

// Minimaler JPEG-Kopf: SOI (FFD8) + SOF-Marker mit Höhe/Breite.
// SOF-Layout: FF Cx | len(2) | precision(1) | height(2) | width(2)
function jpegWithWidth(width, height = 480, marker = 0xC0) {
  const b = Buffer.alloc(20, 0);
  b[0] = 0xFF; b[1] = 0xD8;        // SOI
  b[2] = 0xFF; b[3] = marker;      // SOF0 / SOF2
  b.writeUInt16BE(17, 4);          // Segment-Länge
  b[6] = 8;                        // precision
  b.writeUInt16BE(height, 7);      // Höhe
  b.writeUInt16BE(width, 9);       // Breite
  return b;
}

describe('readJpegWidth', () => {
  test('liest Breite aus SOF0 (baseline)', () => {
    expect(readJpegWidth(jpegWithWidth(320))).toBe(320);
    expect(readJpegWidth(jpegWithWidth(1920))).toBe(1920);
  });

  test('liest Breite aus SOF2 (progressive)', () => {
    expect(readJpegWidth(jpegWithWidth(1280, 720, 0xC2))).toBe(1280);
  });

  test('kein SOF-Marker → null', () => {
    const b = Buffer.from([0xFF, 0xD8, 0xFF, 0xD9, 0, 0, 0, 0, 0, 0, 0, 0]);
    expect(readJpegWidth(b)).toBeNull();
  });
});
