import { forceArgs } from "../cli/forceArgs.ts";
import { cliPrompt } from "../cli/prompts.ts";
import { multiSelectMenuInteractive } from "../cli/selectMenu.ts";
import { TerminalBlock } from "../cli/TerminalLayout.ts";
import type { callback, ITool } from "../types.ts";
import { loadPdf, savePdf } from "util/saveLoadPdf.ts";

export class DeleteFormFields implements ITool {
  name = "deleteFormFields";
  description = "delete multiple form fields from a PDF";
  block?: TerminalBlock;

  async run(pdfPath: string = "") {
    if (!this.block) this.block = new TerminalBlock();
    [pdfPath] = await forceArgs([pdfPath], [[
      "Please provide path to PDF",
      (d) => d?.endsWith(".pdf"),
    ]], this.block);

    const pdf = await loadPdf(pdfPath);
    const form = pdf.getForm();
    const fields = form.getFields();
    let updatesMade = false;
    await multiSelectMenuInteractive(
      `${pdfPath}\nSelect fields to delete:`,
      fields.map<[string, callback]>((
        f,
      ) => [f.getName(), () => {
        while (f.acroField.getWidgets().length) {
          f.acroField.removeWidget(0);
        }
        form.removeField(f);
        updatesMade = true;
      }]),
    );
    if (!updatesMade) return;
    const path = await cliPrompt(
      "Save to path (or hit enter to keep current):",
      this.block,
    ) || pdfPath;
    await savePdf(pdf, path);
  }
  help?: (() => Promise<void> | void) | undefined;
  done?: (() => Promise<void> | void) | undefined;
  setBlock(block: TerminalBlock) {
    this.block = block;
  }
}
export default new DeleteFormFields();
