import 'dart:typed_data';

class PcmSound {
  final Uint8List bytes;
  PcmSound(this.bytes);
}

class AdLibSound {
  final Uint8List bytes;
  AdLibSound(this.bytes);
}

class ImfInstruction {
  final int register;
  final int data;
  final int delay; // Delay in 1/700ths of a second

  ImfInstruction({
    required this.register,
    required this.data,
    required this.delay,
  });
}

class ImfMusic {
  final List<ImfInstruction> instructions;

  ImfMusic(this.instructions);

  factory ImfMusic.fromBytes(Uint8List bytes) {
    List<ImfInstruction> instructions = [];

    // Wolfenstein 3D IMF chunks start with a 16-bit length header (little-endian)
    int actualSize = bytes[0] | (bytes[1] << 8);

    // Start parsing at index 2 to skip the size header
    int limit = 2 + actualSize;
    if (limit > bytes.length) limit = bytes.length; // Safety bounds

    for (int i = 2; i < limit - 3; i += 4) {
      instructions.add(
        ImfInstruction(
          register: bytes[i],
          data: bytes[i + 1],
          delay: bytes[i + 2] | (bytes[i + 3] << 8),
        ),
      );
    }
    return ImfMusic(instructions);
  }
}

typedef WolfMusicMap = List<int>;
