// vim: set ts=2 sw=2 et tw=80:

const solr = "http://localhost:8983/solr/photo";

const q =            document.querySelector("#q");
const docs =         document.querySelector("#docs");
const templateHTML = document.querySelector("#document").innerHTML;

const urlParams = new URLSearchParams(window.location.search);
const query = urlParams.get('q');

let foamtree = null;
let queryResult = null;
let docMap = {}

function buildCard(docData) {
  const emptyOr = s => s ? s : "";
  return templateHTML
    .replaceAll("{{ id }}", emptyOr(docData.id))
    .replaceAll("{{ title }}", emptyOr(docData.t_title))
    .replaceAll("{{ author }}", emptyOr(docData.t_author))
    .replaceAll("{{ description }}", emptyOr(docData.t_description))
    .replaceAll("{{ url }}", emptyOr(docData.img_url))
    .replaceAll("{{ site_url }}", "#");
}

function updateResults(docList) {
	docs.innerHTML = docList.map(d => {
	  return buildCard(d);
	}).reduce((a, b) => a.trim() + b.trim(), "");
  //docs.innerHTML += "<div class='document white'></div>".repeat(28);
}

function filterGroup(info) {
  if (info.groups.length == 0) {
    updateResults(queryResult.response.docs);
    return;
  }

  const list = [].concat(...info.groups.map(e => e.docs)).map(id => docMap[id]);
  updateResults(list);
}

async function buildQuery(e) {
  if (e) e.preventDefault();

  let list = await fetch(solr + "/clustering?q=" + q.value);
  queryResult = await list.json();
  console.log(queryResult);

  updateResults(queryResult.response.docs);
  for (const e of queryResult.response.docs) {
    docMap[e.id] = e;
  }

  let clusters = queryResult.clusters.map(e => {
    return {
      label: e.labels[0],
      weight: e.score,
      docs: e.docs,
    };
  });


  if (foamtree === null) {
    foamtree = new CarrotSearchFoamTree({
      id: "visualization",
      layout: "squarified",
      groupLabelFontFamily: "Fira Sans",
      dataObject: { groups: clusters },
      onGroupSelectionChanged: [filterGroup],
    });
  } else {
    foamtree.set({ dataObject: { groups: clusters }});
  }
};

if (query) {
  q.value = query;
  window.addEventListener("load", () => buildQuery().catch(console.error));
}

document.querySelector("#form").addEventListener("submit", buildQuery);
window.addEventListener('resize', () => {
  if (foamtree) foamtree.resize()
});
