<template>
  <div>
    <HeaderBar />
    <div class="ma-8">
      <div v-if="isPending">Loading...</div>
      <div v-else-if="isError">Error: {{ error?.message }}</div>
      <ul v-else-if="data">
        <li v-for="group in data" :key="group.id">
          <CategoryContainer :licenseGroup="group" />
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import HeaderBar from "./HeaderBar.vue";
import CategoryContainer from "./CategoryContainer.vue";
import { useQuery } from "@tanstack/vue-query";
import { axiosInstance } from "@/client";
import { LicenseGroup, License } from "@/types";
import { search, key } from "@/store";
import MiniSearch from "minisearch";
import { computed, provide } from "vue";

const { isPending, isError, data, error } = useQuery({
  queryKey: ["licenses"],
  queryFn: async () => {
    const res = await axiosInstance.get<LicenseGroup[]>("/licenses");
    console.log(res.data);
    return res.data;
  },
  refetchInterval: 60 * 1000,
});

const searchEngine = computed(() => {
  let minisearch = new MiniSearch({
    fields: ["name", "description", "id"],
    searchOptions: {
      boost: { name: 2 },
      prefix: true,
    },
  });
  let licenses: License[] = [];
  data.value?.forEach((group) => {
    group.licenses.forEach((license) => licenses.push(license));
  });
  console.log(licenses);
  minisearch.addAll(licenses);
  return minisearch;
});

const searching = computed(() => search.value !== "");

const visibleIds = computed(() => {
  return searchEngine.value.search(search.value).map((searchResult) => {
    return searchResult.id;
  });
});

provide(key, {
  visibleIds,
  searching,
});
</script>

<style scoped>
li,
ul {
  list-style-type: none;
}
</style>
