import { takeSelection, getLineId } from "../scrapbox-userscript-std/dom.ts";
import { getIndentCount } from "../scrapbox-userscript-std/text.ts";
import { getEachLatestDate } from "../getEachLatestDate/mod.ts";
import { lightFormat } from "../date-fns/lightFormat.ts";
import { Scrapbox } from "../scrapbox-jp%2Ftypes/userscript.ts";
declare const scrapbox: Scrapbox;

export const getSnippet = (project: string): {
  title: string;
  body: string;
} | undefined => {
  if (scrapbox.Layout !== "page") return;
  
  const selection = takeSelection();
  const { start, end } = selection.getRange();
  const id = getLineId(Math.min(start.line, end.line));
  const title = scrapbox.Page.title;
  const from = `${
    project !== scrapbox.Project.name ? `/${scrapbox.Project.name}/` : ""
  }${title}${id ? `#${id}` : ""}`;
  
  const lines = selection.getSelectedText()
    .replace(/\[([^\]\/]+).icon\]/gm, `[${
      project !== scrapbox.Project.name ? `/${scrapbox.Project.name}/` : ""
    }$1.icon]`)
    .split("\n");
  const minIndentCount = Math.min(...lines.map((text) => getIndentCount(text)));
  const dates = getEachLatestDate(scrapbox.Page.lines.slice(
    Math.min(start.line, end.line),
    Math.max(start.line, end.line) + 1
  ).map(({ updated }) => new Date(updated * 1000)));
  const body = [
    `from [${from}]`,
    ...lines.map((text) => text.slice(minIndentCount)),
    "",
    ...dates.map((date) => `#${lightFormat(date, "yyyy-MM-dd HH:mm:ss")}`),
  ].join("\n");
  return { title, body };
};