import {
  transport, createTask, toString
} from "../takker99%2Ftakker-scheduler/deps.ts";
import {
  parse, toTaskLine
} from "../takker99%2Ftakker-scheduler/workflow.ts";
import {
  caret, getLines, replaceLines
} from "../scrapbox-userscript-std/dom.ts";
import type { Scrapbox } from "../scrapbox-jp%2Ftypes/userscript.ts";
declare const scrapbox: Scrapbox;

export const taskCommon = [
  {key: 'alt+a alt+c', command: () => {
    (async () => {
      const [start, end] = getLineRange();
      const text = getLines().slice(start, end + 1).map((line) => {
        const text = line.text;
        const link = line.text.match(/\[([^\]]+)\]/)?.[1];
        if (!link) return text;
        const result = parse(link);
        if (!result || !result.ok) return text;
        const task = result.value;
        if (task.freshness?.status === "done") return text;
        const taskLine = toTaskLine(task);
        taskLine.title = `[${link}]`;
        if (!taskLine) return text;
        return toString(taskLine);
      }).join("\n");
      await replaceLines(start, end, text);
      await createTask();
    })();
    return false;
  },},
  {key: 'alt+a alt+m', command: () => {
    if (scrapbox.Layout !== "page") return;
    transport({
      from: {
        project: scrapbox.Project.name,
        title: scrapbox.Page.title,
      },
      to: "takker-memex",
    });
    return false;
  },},
];

/** 選択範囲に含まれる行かカーソルがいる行を返す
 *
 * ported from https://github.com/takker99/takker-scheduler/blob/0.7.6/commands/getLineRange.ts
 */
const getLineRange = (): readonly [number, number] => {
  const { selectionRange: { start, end }, selectedText, position } = caret();
  return selectedText === ""
    ? [position.line, position.line]
    : start.line > end.line
    ? [end.line, start.line]
    : [start.line, end.line] as const;
};