import { Plugin } from "..";

export function parseMetadata(file: string) {
  if (!/^=+$/gm.test(file)) return;
  const splitfile = file.split("\n");
  let properties: Record<string, string> | undefined;
  for (let i = 0; i < splitfile.length; i++) {
    if (!properties) properties = {};
    const line = splitfile[i];
    if (/^=+$/gm.test(line)) break;
    const parts = line.split("=");
    if (parts.length !== 2) break;
    properties[parts[0].trim()] = parts[1].trim();
  }
  return properties;
}

export default class MarkdownMetadataGenerator extends Plugin {
  build: undefined;

  name = "markdown-metadata";
  rewriteTriggers = ["md"];
  renameTo = "json";
  longLasting = false;

  async rewriteFile(file: string, filePath: string) {
    const metadata = parseMetadata(file);
    if (!metadata) return;
    return JSON.stringify(metadata);
  }
}
