/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />

import { useStatusBar } from "../scrapbox-userscript-std/dom.ts";
import { updateCodeFile } from "../scrapbox-userscript-std/websocket.ts";
import { Scrapbox } from "../scrapbox-jp%2Ftypes/userscript.ts";
declare const scrapbox: Scrapbox;

scrapbox.PageMenu.addMenu({
  title: "Update dev UserScript",
  image: "https://i.gyazo.com/95e1d28e25db16bf7c4fdeeb16452179.png",
  onClick: async () => {
    const content = await navigator.clipboard.readText();
    if (!content?.trim?.()) return;
    const bar = useStatusBar();
    bar.render({
      type: "group",
      items: [{ type: "spinner" }, {
        type: "text",
        text: "Update import-dev/mod.js...",
      }],
    });
    try {
      await updateCodeFile({ filename: "mod.js", content }, "takker", "import-dev");
      bar.render({
        type: "group",
        items: [{ type: "check-circle" }, {
          type: "text",
          text: "Updated",
        }],
      });
    } catch(e: unknown) {
      console.error(e);
      if(!(e instanceof Error)) throw e;
      bar.render({
        type: "group",
        items: [{ type: "exclamation-triangle" }, {
          type: "text",
          text: `${e.name} ${e.message}`,
        }],
      });
    } finally {
      setTimeout(() => bar.dispose(), 2000);
    }
  },
});