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

import { handle_file_select } from "./filesystem.js";
var search_input = document.getElementById("file-search-dialog-input");
search_input.addEventListener("input", () => {
  search_files();
});

function search_files() {
  var text = search_input.innerText;
  invoke("search_files", {
    searchstring: text,
    basepath: "$HOME/Documents/Knowledgebase",
    filter: ["md"],
  }).then((ret) => {
    var tag_id = document.getElementById("file-search-results");
    var result_div = "";
    console.log(ret);
    ret.forEach((element) => {
      result_div += element;
    });
    console.log(result_div);
    tag_id.innerHTML = result_div;
  });
}

let filetree = document.getElementById("file-search-results");
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
  console.log("updating on click");
  var anchors = document.getElementsByClassName("file-search-button");
  for (var i = 0; i < anchors.length; i++) {
    var anchor = anchors[i];
    anchor.onclick = function () {
      handle_file_select(this.parentElement.id);
    };
  }
};

const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(filetree, config);
