<template>
  <div class="home">
    <h1>
      Welcome to
      <em v-if="infoData?.name"> "{{ infoData.name }}" </em>
      <template v-else> UpEnd </template>
      !
    </h1>
    <ul v-if="latestFiles">
      <li v-for="file in latestFiles" :key="file.hash">
        <router-link :to="{ name: 'inspect', params: { address: file.hash } }">
          <span class="file-path">{{ file.path }}</span>
        </router-link>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { IFile, VaultInfo } from "@/types/base";
import useSWRV from "swrv";
import { computed, defineComponent } from "vue";
import { fetcher } from "../utils";
import { parseISO } from "date-fns";

export default defineComponent({
  name: "Home",

  setup() {
    const { data: infoData } = useSWRV<VaultInfo, unknown>(
      "/api/info",
      fetcher
    );

    const { data: latestFilesRaw } = useSWRV<IFile[], unknown>(
      "/api/files/latest",
      fetcher
    );

    const latestFiles = computed(() => {
      if (latestFilesRaw?.value) {
        return latestFilesRaw.value.map((file) => {
          return {
            ...file,
            added: parseISO(file.added),
            mtime: parseISO(file.added),
          };
        });
      }
    });

    return {
      infoData,
      latestFiles,
    };
  },
});
</script>

<style lang="scss">
h1 {
  text-align: center;
  font-weight: normal;
}
</style>
