const { convertFileSrc, invoke } = window.__TAURI__.core;
const { open } = window.__TAURI__.dialog;

let text = "";
let placeholder_path = "FILEPATH";
let path_template = convertFileSrc(placeholder_path);

let textarea = document.getElementById("markdown_input");

// TODO move to place, where the knowledgebase is created...
invoke("initialize_database", {
  basepath: "~/Documents/Knowledgebase",
  pathtemplate: path_template,
}).then((ret) => {});
invoke("get_basepath").then((ret) => {
  if (!ret) {
    const setup_dialog = document.getElementById("setup-dialog");
    setup_dialog.show();
  } else {
    console.log(ret);
  }
});

document.getElementById("knowledgebase-button").onclick = async function () {
  const file = await open({
    multiple: false,
    directory: true,
  });

  const path_text = document.getElementById("knowledgebase-path");
  path_text.innerText = file;
  invoke("set_basepath", { path: file }).then((ret) => {
    if (ret) {
      const setup_dialog = document.getElementById("setup-dialog");
      console.log("hiding");
      setup_dialog.close();
      location.reload();
    }
  });
  console.log(file);
};
//
export function render_markdown() {
  text = textarea.innerText;
  invoke("parse_markdown", {
    document: text,
    pathtemplate: path_template,
  }).then((ret) => {
    var tag_id = document.getElementById("rendered_markdown");
    tag_id.innerHTML = "<pre>".concat("", ret).concat("", "</pre>");
  });
}
textarea.addEventListener("input", () => {
  render_markdown();
});

// Random tree
// const N = 300;
// const gData = {
//   nodes: [...Array(N).keys()].map(i => ({ id: i })),
//   links: [...Array(N).keys()]
//     .filter(id => id)
//     .map(id => ({
//       source: id,
//       target: Math.round(Math.random() * (id-1))
//     }))
// };
// const Graph = new ForceGraph(
//   (document.getElementById('graph'))
//     .linkDirectionalParticles(2)
//     .graphData(gData);
