import { Marked } from "marked";
const widget_map = {
    test: () => import("~/components/viewer/widgets/TestWidget.vue"),
    table: () => import("~/components/viewer/widgets/TableWidget.vue"),
    roll: () => import("~/components/viewer/widgets/RollWidget.vue"),
};

const componentCache = {}

const GetWidget = (type) => {
  if (!componentCache[type]) {
    componentCache[type] = defineAsyncComponent(
      widget_map[type]
    )
  }

  return componentCache[type]
}


const marker = new Marked();

const extension = {
  name: "something",
  level: "block",

  tokenizer(src) {
    const rule = /^@(\w+)\n([\s\S]+?)\n@end/;
    const match = rule.exec(src);

    if (!match) return;

    return {
      type: "something",
      raw: match[0],
      name: match[1],
      text: match[2],
    };
  },

  renderer(token) {
    return `<div class="vue-component" data-component="${token.name}" data-content="${token.text}"></div>`;
  },
};

const inlineExtension = {
  name: "something_inline",
  level: "inline",
  start(src) {
    return src.indexOf("@");
  },

  tokenizer(src) {
    const rule = /^@(\w+)\s*\[([^\]]*)\]/;
    const match = rule.exec(src);
    if (!match) return;

    return {
      type: "something_inline",
      raw: match[0],
      name: match[1],
      text: match[2],
    };
  },

  renderer(token) {
    return `<span class="vue-component" data-component="${token.name}" data-content="${token.text}"></span>`;
  },
};

marker.use({
  extensions: [extension, inlineExtension],
});

function ParseMarkdown(source) {
  return marker.parse(source || "");
}

export { ParseMarkdown, GetWidget };