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

function fixture(type: number) {
  const mainIfd = 8;
  const bits = 158;
  const subIfd = 164;
  const subBits = 302;
  const pixels = 308;
  const subPixels = pixels + 64 * 64 * 3;
  const bytes = new Uint8Array(subPixels + 8 * 8 * 3);
  const view = new DataView(bytes.buffer);
  view.setUint16(0, 0x4949, true);
  view.setUint16(2, 42, true);
  view.setUint32(4, mainIfd, true);
  function ifd(offset: number, size: number, data: number, bitsOffset: number, sub: boolean) {
    const tags = [
      [256, 4, 1, size], [257, 4, 1, size], [258, 3, 3, bitsOffset],
      [259, 3, 1, 1], [262, 3, 1, 2], [273, 4, 1, data],
      [277, 3, 1, 3], [278, 4, 1, size], [279, 4, 1, size * size * 3],
      [284, 3, 1, 1], [339, 3, 1, 1], ...(sub ? [[330, type, 1, subIfd]] : []),
    ];
    view.setUint16(offset, tags.length, true);
    tags.forEach(([tag, kind, count, value], i) => {
      const p = offset + 2 + i * 12;
      view.setUint16(p, tag!, true); view.setUint16(p + 2, kind!, true);
      view.setUint32(p + 4, count!, true); view.setUint32(p + 8, value!, true);
    });
    for (let i = 0; i < 3; i++) view.setUint16(bitsOffset + i * 2, 8, true);
    for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
      const p = data + (y * size + x) * 3;
      if (x >= size / 4 && x < size * 3 / 4 && y >= size / 4 && y < size * 3 / 4) bytes.set([255, 128, 0], p);
    }
  }
  ifd(mainIfd, 64, pixels, bits, true);
  ifd(subIfd, 8, subPixels, subBits, false);
  return bytes;
}

test("Files previews TIFF with standard IFD type 13 SubIFDs", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("TIFF preview", {
    "subifd.tiff": fixture(13), "control-long.tiff": fixture(4),
  });
  const thread = await t3.thread({ project, title: "TIFF preview", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const open = async (name: string) => {
    await browser.locator(`[data-item-path="${name}"]`).tap();
    await screen.getByText(/64 × 64|Unable to load image\./).waitFor();
  };
  await open("control-long.tiff");
  await app.screenshot("control-long");
  await open("subifd.tiff");
  await app.screenshot("subifd-preview");
  await expect(screen.getByText("64 × 64", { exact: true })).toBeVisible();
});
