import { transport } from "./mod.ts";
import {
  useStatusBar,
  encodeTitleURI,
} from "../scrapbox-userscript-std/dom.ts";
import type { Scrapbox } from "../scrapbox-jp%2Ftypes/userscript.ts";
declare const scrapbox: Scrapbox;

export const transportPage = async (): Promise<string | undefined> => {
  const title = scrapbox.Page.title!;
  const from = scrapbox.Project.name;
  const to = globalThis.prompt(
    `Take "/${from}/${title}" from "${from}" to:`,
    "takker",
  );
  if (!to) return;
  
  const { render, dispose } = useStatusBar();
  render(
    { type: "spinner" },
    { type: "text", text: `/${from}/${title} → /${to}/${title}` }
  );
  try {
    const result = await transport(title, { from, to, merge: true });
    if (!result.success) {
      render(
        { type: "exclamation-triangle" },
        { type: "text", text: `${result.name} ${result.message}`,
        },
      );
      return;
    }
    
    render(
      { type: "check-circle" },
      {
        type: "text",
        text: `Moved ${result.dup ? "and merged " : ""}to "/${to}/${title}".`
      },
    );
    return `https://scrapbox.io/${to}/${encodeTitleURI(title)}`;
  } catch(e: unknown) {
    render(
      { type: "exclamation-triangle" },
      { type: "text", text: e instanceof Error ?
        `${e.name} ${e.message}` :
        `Unknown error! (see developper console)`,
      },
    );
    console.error(e);
  } finally {
    setTimeout(() => dispose(), 1000);
  }
};