import {
  parse as parseYaml,
} from "https://deno.land/std@0.170.0/encoding/yaml.ts";

function trimSubstring(str: string, start: number, end: number) {
  while (
    str[start] === " " || str[start] === "\t" || str[start] === "\r" ||
    str[start] === "\n"
  ) {
    start++;
  }
  return str.substring(start, end);
}

interface Doc {
  metadata: Record<string, string | string[]>;
  content: string;
}

export function parse(content: string): Doc {
  if (!content.startsWith("---")) {
    return {
      metadata: {},
      content: content,
    };
  }
  const index = content.indexOf("\n---", 3);
  const meta = content.substring(3, index);
  const c = trimSubstring(content, index + 4, content.length);
  const metadata = parseYaml(meta) as Record<string, string | string[]>;
  return {
    metadata: metadata,
    content: c,
  };
}

export async function readMarkdownDoc(path: string): Promise<Doc> {
  const doc = await Deno.readTextFile(path);
  return parse(doc);
}
