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

let tab: WindowProxy | null;
let prevHTML = "";
const fileName = "index.html";
let blobURL: string | undefined = undefined;

const findHTMLBlock = (): string | undefined => {
  if (scrapbox.Layout !== "page") return;
  let lines: string[] = [];
  let indent = 0;
  for (const line of scrapbox.Page.lines) {
    if (!("codeBlock" in line)) continue;
    if (line.codeBlock.filename !== fileName) continue;
    if (line.codeBlock.start) {
      // コードブロックのタイトルのindent数分だけ削る
      indent = line.codeBlock.indent;
      continue;
    }
    lines.push([...line.text].slice(indent).join(""));
  }
  if (lines.length === 0) return;
  return lines.join("\n");
};

const updateTab = () => {
  const html = findHTMLBlock();
  if (!html) return;
  if (prevHTML === html) return;
  console.debug({before: prevHTML, after:html});
  prevHTML = html;
  if (blobURL) URL.revokeObjectURL(blobURL);
  blobURL = URL.createObjectURL(
    new Blob([html], { type: "text/html" })
  );
  if (!tab) {
    tab = window.open(blobURL);
  } else {
    tab.location.href = blobURL;
  }
};

let timer: number | undefined;
const callback = () => {
  clearTimeout(timer);
  if (tab?.closed) {
    scrapbox.off("lines:changed", callback);
    return;
  }
  timer = setTimeout(updateTab, 500);
};
updateTab();
scrapbox.on("lines:changed", callback);