// @license magnet:?xt=urn:btih:1f739d935676111cfff4b4693e3816e664797050&dn=gpl-3.0.txt GPL-v3-or-Later
// How many characters to include on either side of match keyword
const summaryInclude = 60;

// Options for fuse.js
let fuseOptions = {
  shouldSort: true,
  includeMatches: true,
  tokenize: true,
  matchAllTokens: true,
  threshold: 0.0,
  location: 0,
  distance: 100,
  maxPatternLength: 64,
  minMatchCharLength: 3,
  keys: [
    { name: "title", weight: 0.8 },
    { name: "categories", weight: 0.6 },
    { name: "tags", weight: 0.5 },
    { name: "contents", weight: 0.4 },
  ],
};

function getUrlParameter(name) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  let regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
  let results = regex.exec(location.search);
  return results === null
    ? ""
    : decodeURIComponent(results[1].replace(/\+/g, " "));
}

let searchQuery = getUrlParameter("q");

clearCache();
if (searchQuery) {
  document.getElementById("search-query").value =
    searchQuery.charAt(0).toUpperCase() + searchQuery.slice(1);
  executeSearch(searchQuery);
} else {
  document.getElementById("search-results").innerHTML =
    '<p class="no-results">Please enter a word or phrase above</p>';
}

function executeSearch(searchQuery, section) {
  console.log("executeSearch.section:", section);
  console.log("executeSearch.searchData:", searchData);
  let fuse = new Fuse(searchData, fuseOptions);
  let result = fuse.search(searchQuery);
  let contentPath = searchData[0].permalink;
  if (contentPath.startsWith("file:///")) {
    if (result.length > 0) {
      Android.clearSearchText();
      populateResults(result, section, searchQuery);
      Android.setSearchText(searchQuery);
    } else {
      Android.clearSearchText();
      document.getElementById("search-results").innerHTML =
        '<p class="no-results">No matches found</p>';
    }
  }
  if (result.length > 0) {
    populateResults(result, section, searchQuery);
  } else {
    document.getElementById("search-results").innerHTML =
      '<p class="no-results">No matches found</p>';
  }
}

function populateResults(result, section, searchQuery) {
  result.forEach(function (value, key) {
    console.log("populateResults: value.item.section =", value.item.section);
    let searchPath;
    if (value.item.permalink.startsWith("file")) {
      searchPath = value.item.permalink.replace(
        "file:///data/user/0/org.jembi.healthconnect.guides.eml/www/guide/",
        ""
      );
    } else {
      searchPath = value.item.permalink.replace(
        "https://cms-dev.rsahealth.org/eml/",
        ""
      );
    }
    let newSearchPath = searchPath.replace(/\/index.html/, "").split("/");
    if (section != "all" && section != value.item.section) {
      return;
    }
    let contents = value.item.contents;
    // let newPermalink = value.item.permalink+'?q='+searchQuery;
    let snippet = "";
    let snippetHighlights = [];
    snippetHighlights.push(searchQuery);
    if (snippet.length < 1) {
      snippet += contents.substring(0, summaryInclude * 2);
    }
    snippet += "…";

    // Lifted from https://stackoverflow.com/posts/3700369/revisions
    var elem = document.createElement("textarea");
    elem.innerHTML = snippet;
    var decoded = elem.value;

    // Pull template from hugo template definition
    let frag = document
      .getElementById("search-result-template")
      .content.cloneNode(true);
    // Replace values
    frag.querySelector(".search_summary").setAttribute("id", "summary-" + key);
    frag
      .querySelector(".search_link")
      .setAttribute("href", ".." + value.item.permalink);
    frag.querySelector(".search_title").innerHTML =
      value.item.title +
      //"<br />" +
      " " +
      // newSearchPath[0] +
      // ":" +
      // " " +
       newSearchPath[1] +
      "<br />" +
      // "context" +
      // ":" +
       " " +
      newSearchPath[2];		  
    frag.querySelector(".search_snippet").textContent = decoded;
    let tags = value.item.tags;
    if (tags) {
      frag.querySelector(".search_tags").textContent = tags;
    } else {
      frag.querySelector(".search_iftags").remove();
    }
    let categories = value.item.categories;
    if (categories) {
      frag.querySelector(".search_categories").textContent = categories;
    } else {
      frag.querySelector(".search_ifcategories").remove();
    }
    // snippetHighlights.forEach(function (snipvalue, snipkey) {
    //     let markjs = new Mark(frag);
    //     markjs.mark(snipvalue);
    // });
    document.getElementById("search-results").appendChild(frag);
  });
}

// @license-end
