import { stitchTypes } from '$lib/file-renderer/pattern';

/**
 * Decodes a single byte with EXP format rules.
 * Values above 128 are negative numbers encoded with bitwise operations.
 *
 * @param {number} input - A signed 8-bit integer (-128 to 127).
 * @returns {number} - Decoded signed integer.
 */
function expDecode(input) {
  return input > 128 ? -(~input & 0xff) - 1 : input;
}

/**
 * Reads an EXP format file and adds stitches to the given pattern.
 *
 * @param {EmbroideryFileView} file - A DataView representing the binary EXP file content.
 * @param {EmbroideryPattern} pattern - The pattern object with addStitchRel and invertPatternVertical methods.
 * @returns {void}
 */
export function expRead(file, pattern) {
  let index = 0;
  const byteCount = file.byteLength;

  while (index < byteCount) {
    let flags = stitchTypes.normal;
    let b0 = file.getInt8(index++);
    let b1 = file.getInt8(index++);

    if (b0 === -128) {
      if (b1 & 1) {
        b0 = file.getInt8(index++);
        b1 = file.getInt8(index++);
        flags = stitchTypes.stop;
      } else if (b1 === 2 || b1 === 4) {
        b0 = file.getInt8(index++);
        b1 = file.getInt8(index++);
        flags = stitchTypes.trim;
      } else if (b1 === -128) {
        b0 = file.getInt8(index++);
        b1 = file.getInt8(index++);
        b0 = 0;
        b1 = 0;
        flags = stitchTypes.trim;
      }
    }

    const dx = expDecode(b0);
    const dy = expDecode(b1);

    pattern.addStitchRel(dx, dy, flags, true);
  }

  pattern.addStitchRel(0, 0, stitchTypes.end);
  pattern.invertPatternVertical();
}
