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

test("ODS time values fall back only when display text is absent", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("ODS time preview");
  execFileSync("python3", ["-c", `
import sys, zipfile
from pathlib import Path
for filename, paragraph in [("stored-time.ods", ""), ("display-time.ods", "<text:p>03:30:00</text:p>")]:
    xml = '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet><table:table table:name="Time"><table:table-row><table:table-cell office:value-type="time" office:time-value="PT03H30M00S">' + paragraph + '</table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>'
    with zipfile.ZipFile(Path(sys.argv[1]) / filename, "w") as archive:
        archive.writestr("mimetype", "application/vnd.oasis.opendocument.spreadsheet")
        archive.writestr("content.xml", xml)
`, project]);
  const thread = await t3.thread({ project, title: "ODS time cells", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const openFile = async (path: string) => {
    await expect.poll(() => browser.evaluate((path) => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
        if (row) { row.click(); return true; }
      }
      return false;
    }, path)).toBe(true);
  };
  await openFile("display-time.ods");
  await expect(screen.getByText("03:30:00", { exact: true })).toBeVisible();
  await app.screenshot("display-text-wins");
  await openFile("stored-time.ods");
  // Wait for the new preview rather than photographing the preceding workbook.
  await expect(screen.getByText("03:30:00", { exact: true })).not.toBeVisible();
  await app.screenshot("stored-time-fallback");
  await expect(screen.getByText("PT03H30M00S", { exact: true })).toBeVisible();
});
