/*
 * editor-support.test.ts
 *
 * Copyright (C) 2023 Posit Software, PBC
 */

import { docs } from "../../utils.ts";
import { test } from "../../test.ts";
import { assertEquals } from "testing/asserts";
import { isWindows } from "../../../src/deno_ral/platform.ts";

async function runEditorSupportCrossref(doc: string) {
  const cmdLine: string = isWindows ?
    "../package/dist/bin/quarto.cmd" :
    "../package/dist/bin/quarto";

  const cmd = new Deno.Command(cmdLine, {
    args: ["editor-support", "crossref"],
    stdin: "piped",
    stdout: "piped",
    stderr: "piped",
  });
  const child = cmd.spawn();
  const writer = child.stdin.getWriter();
  const buf = new TextEncoder().encode(
    Deno.readTextFileSync(doc),
  );
  await writer.write(buf);
  writer.releaseLock();
  await writer.close();
  const outputBuf = await child.output();
  const status = await child.status;
  assertEquals(status.code, 0);
  const output = new TextDecoder().decode(outputBuf.stdout);
  const json = JSON.parse(output);
  return json;
}

test({
  name: "editor-support:crossref:smoke-1",
  context: {},
  execute: async () => {
    const json = await runEditorSupportCrossref(docs("crossrefs/sections.qmd"));
    assertEquals(json.entries[0].key, "sec-introduction");
    assertEquals(json.entries[0].caption, "Introduction");
  },
  verify: [],
  type: "smoke",
});

function smokeTestCrossref(name: string, doc: string) {
  test({
    name,
    context: {},
    execute: async () => {
      await runEditorSupportCrossref(doc);
    },
    verify: [],
    type: "smoke",
  });
}

const smokeTestCrossrefDocs = [
  "crossrefs/editor-support/unnumbered-crossrefs.qmd",
  "crossrefs/editor-support/all.qmd",
  "crossrefs/editor-support/crossref-with-raw-latex.qmd",
];
for (const doc of smokeTestCrossrefDocs) {
  smokeTestCrossref(
    `editor-support:crossref:smoke-${doc}`,
    docs(doc),
  );
}
