/// <reference lib="dom" />
import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const fixture = new Uint8Array(readFileSync(new URL("../../apps/web/test/fixtures/disk-images/demo.dmg", import.meta.url)));
function image(name: string, unreadable = false) {
  const trailer = fixture.slice(-512);
  const view = new DataView(trailer.buffer);
  const offset = Number(view.getBigUint64(216));
  const length = Number(view.getBigUint64(224));
  let plist = new TextDecoder().decode(fixture.subarray(offset, offset + length)).replaceAll("disk image (Apple_HFS : 4)", name);
  if (unreadable) {
    const table = new Uint8Array(284);
    const v = new DataView(table.buffer);
    table.set(new TextEncoder().encode("mish"));
    v.setUint32(200, 2);
    v.setUint32(204, 0x80000006);
    v.setBigUint64(220, 4n);
    v.setBigUint64(236, 16n);
    v.setUint32(244, 0xffffffff);
    // A supported-to-parse UDIF table with an unsupported bzip2 chunk, before the real volume.
    plist = plist.replace(/(<key>blkx<\/key>\s*<array>)/, `$1<dict><key>CFName</key><string>Unreadable candidate</string><key>Data</key><data>${Buffer.from(table).toString("base64")}</data></dict>`);
  }
  const bytes = new TextEncoder().encode(plist);
  view.setBigUint64(224, BigInt(bytes.length));
  const result = new Uint8Array(offset + bytes.length + 512);
  result.set(fixture.subarray(0, offset));
  result.set(bytes, offset);
  result.set(trailer, offset + bytes.length);
  return result;
}
const unsupported = "Previews support disk images with an HFS+ volume.";
const apfs = "This disk image uses APFS, which cannot be previewed yet.";
const compression = "This disk image uses a compression format that cannot be previewed. Zlib and ADC images are supported.";
const cases = [
  ["Original", "disk image (Apple_HFS : 4)", false, "volume"],
  ...["DDM Backup", "GPT Backup", "MBR Archive", "Driver Disk", "OS Patches"].map(label => [label, label, false, "volume"] as const),
  ["Typed-DDM", "Driver Descriptor Map (DDM : -1)", false, unsupported],
  ["Unreadable-then-HFS", "disk image (Apple_HFS : 4)", true, "volume"],
  ["Unreadable-then-APFS", "Container (Apple_APFS : 2)", true, apfs],
  ["Unreadable-only", "free (Apple_Free : 4)", true, compression],
] as const;

test("Disk image labels and unreadable partitions preserve the correct Files preview", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Disk image examples", Object.fromEntries(cases.map(([file, name, bad]) => [`${file}.dmg`, image(name, bad)])));
  const thread = await t3.thread({project, title: "Inspect disk images", messages: ["Start"]});
  await browser.setViewport({width: 1600, height: 1000});
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", {exact:false}).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("button", "Maximize panel", {exact:true}).tap();
  const results: string[] = [];
  for (const [file, , , wanted] of cases) {
    await screen.getByRole("treeitem", `${file}.dmg`, {exact:true}).tap();
    await screen.getByText(/Demo 1\.0|Previews support disk images with an HFS\+ volume\.|This disk image uses (APFS|a compression format)/).waitFor({timeout:120000});
    const text = await browser.evaluate(() => document.querySelector("[data-right-panel-surface-content]")?.textContent ?? "");
    results.push(wanted === "volume" ? (text.includes("Demo 1.0") && text.includes("Demo.app") && text.includes("Applications") ? "volume" : text.includes(unsupported) ? unsupported : text.includes(compression) ? compression : text) : text.includes(wanted) ? wanted : text.includes(compression) ? compression : text);
    await app.screenshot(file.toLowerCase().replaceAll(" ", "-"));
  }
  await expect(results).toEqual(cases.map(row => row[3]));
});
